我读了很多关于用正则表达式替换 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>
,这在我的情况下是 Not Acceptable 。
我也尝试过使用下面的正则表达式,但没有运气。
str=str.replaceAll("(?<!\\S)2017(?!\\S)", "****");
请不要将其标记为重复并将其关闭,因为没有答案按预期工作。
最佳答案
如果您尝试替换引号中的“2017”,只需明确执行即可:
str = str.replace("\"2017\"", "\"****\"");
关于java - 使用java替换xml字符串中精确匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808418/