我读了很多关于正则表达式的文章来替换xml值中的字符串。在许多文章中,大多数人接受了
的答案str=str.replaceAll("\\b2017\\b", "****");
但这不符合预期,并在其他地方取代2017年。下面是我的例子。
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=\"customerconfirmation@email.com\"> "+
" <PaymentCard ExpireDate=\"2017\"> "+
" <CardType Code=\"VISA\"/> "+
" <CardHolderName>Test Booking</CardHolderName> "+
" <Telephone PhoneNumber=\"1234567890\"/> "+
" <Email>errorreporting@email.com</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);
}
}
当我运行此计划时,预期结果<PaymentCard ExpireDate="2017">
应替换为<PaymentCard ExpireDate="****">
,但同时将<PurchaseDate>2017-08-21</PurchaseDate>
中的2017年值替换为<PurchaseDate>****-08-21</PurchaseDate>
这是不可接受的我的情况。
我尝试使用以下正则表达式,但没有运气。
str=str.replaceAll("(?<!\\S)2017(?!\\S)", "****");
请不要将此标记并关闭为重复,因为没有答案按预期工作。
答案 0 :(得分:1)
如果您尝试在引号中替换“2017”,请明确这样做:
str = str.replace("\"2017\"", "\"****\"");
答案 1 :(得分:0)
您可以使用以下正则表达式:
str=str.replaceAll("(2017(?!-))", "****");