Reputation: 95
I read many articles about the regex to replace the string in xml value. In many articles most of the peoples accepted answers for
str=str.replaceAll("\\b2017\\b", "****");
But this is not working as expected and replacing 2017 in other place also. below is my example.
public class StringTest {
public static void main(String[] args) {
String str=
"<OTA_InsuranceBookRQ xmlns=\"http://www.opentravel.org/OTA/2003/05\" Version=\"2.001\"> "+
" <POS> "+
" <Source> "+
" <TPA_Extensions> "+
" <ProductCode>101468</ProductCode> "+
" <PurchaseDate>2017-08-21</PurchaseDate> "+
" <TransactionType>PURCHASE</TransactionType> "+
" <SubmissionType>MerchantXMLPurchase</SubmissionType> "+
" </TPA_Extensions> "+
" </Source> "+
" </POS> "+
" <PlanForBookRQ PlanID=\"245235\"> "+
" <InsCoverageDetail> "+
" <CoveredTrips> "+
" <CoveredTrip DepositDate=\"2017-08-11T00:00:00.000Z\" End=\"2017-09-03\" FinalPayDate=\"2017-08-14T00:00:00.000Z\" Start=\"2017-09-02\"> "+
" <Destinations> "+
" <Destination> "+
" <StateProv/> "+
" <CountryName>Germany</CountryName> "+
" </Destination> "+
" </Destinations> "+
" <Operators> "+
" <Operator CompanyShortName=\"Delta\" TravelSector=\"Airline\"/> "+
" <Operator CompanyShortName=\"Carnival\" TravelSector=\"CruiseLine\"/> "+
" </Operators> "+
" </CoveredTrip> "+
" </CoveredTrips> "+
" </InsCoverageDetail> "+
" <InsuranceCustomer> "+
" <PaymentForm CostCenterID=\"ONLINE\" GuaranteeID=\"243356\" RPH=\"\" Remark=\"[email protected]\"> "+
" <PaymentCard ExpireDate=\"2017\"> "+
" <CardType Code=\"VISA\"/> "+
" <CardHolderName>Test Booking</CardHolderName> "+
" <Telephone PhoneNumber=\"1234567890\"/> "+
" <Email>[email protected]</Email> "+
" <CardNumber EncryptedValue=\"4111111111111111\"/> "+
" <SeriesCode EncryptedValue=\"Agent who sold policy\"/> "+
" </PaymentCard> "+
" </PaymentForm> "+
" </InsuranceCustomer> "+
" </PlanForBookRQ> "+
"</OTA_InsuranceBookRQ>";
str=str.replaceAll("\\b2017\\b", "****");
System.out.println(str);
}
}
when i ran this program expected result is <PaymentCard ExpireDate="2017">
should replace with <PaymentCard ExpireDate="****">
but along with that it also replacing 2017 value in <PurchaseDate>2017-08-21</PurchaseDate>
as <PurchaseDate>****-08-21</PurchaseDate>
which is not acceptable in my case.
i tried with below regex also but no luck.
str=str.replaceAll("(?<!\\S)2017(?!\\S)", "****");
please do not mark and close this as duplicate since no answers are working as expected.
Upvotes: 1
Views: 351
Reputation: 633
You can use the following regex:
str=str.replaceAll("(2017(?!-))", "****");
Upvotes: 0
Reputation: 50756
If you're trying to replace "2017" in quotes, just do so explicitly:
str = str.replace("\"2017\"", "\"****\"");
Upvotes: 1