使用正则表达式

时间:2018-01-29 17:10:58

标签: java regex replace

我在下面有以下字符串

REQUEST DATA : uri=/XXX/XXXX;payload={"creditCardNumber": "PPPPP","expirationDate": "PPPP","transactionAmount": "164.7","arrivalDate": "08/17/2018","departureDate": "08/24/2018","merchantNumber": "MMMMMM","terminalId": "TTTT","userId": "UUUUU","clientTransactionId": "TTTTTT","applicationName": "AAA","bankCode": "AAAA","industryName": "RRRR","partialAuthorizationRequest": "N","addressVerificationData": "DDDDD"]

我想从" PPPPP"中取代creditCardNumber的值。至" XXXX"。 我编写了以下代码,但它正在替换所有内容,包括字符串creditCardNumber,这不是我想要的。

    String re1=".*?";   // Non-greedy match on filler
    String re2="(\"creditCardNumber\")";    // Double Quote String 1
    String re3="(:)";   // Any Single Character 1
    String re4="(\\s+)";    // White Space 1
    String re5="(\".*?\")"; // Double Quote String 2

    Pattern p = Pattern.compile(re1+re2+re3+re4+re5,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(message);
    if (m.find())
    {
        String string1=m.group(1);
        String c1=m.group(2);
        String ws1=m.group(3);
        String string2=m.group(4);
        String replacement = string1.toString() + c1.toString() + ws1.toString() + string2.toString();
        String finalReplacement = message.replaceFirst(re1 + re2 + re3 + re4 + re5 ,"XXXXXXXXX");
        this.logger.debug(finalReplacement);
    }
}

谢谢!

0 个答案:

没有答案