Java正则表达式将组与字符串进行比较

时间:2015-05-28 16:32:41

标签: java regex

我正在尝试使用正则表达式进行替换。相关的代码如下:

String msg ="    <ClientVerificationResult>\n " +
            "      <VerificationIDCheck>Y</VerificationIDCheck>\n" +
            "    </ClientVerificationResult>\n";

String regex = "(<VerificationIDCheck>)([Y|N])(</VerificationIDCheck>)";
String replacedMsg= msg.replaceAll(regex, "$2".matches("Y") ? "$1YES$3" : "$1NO$3") ;
System.out.println(replacedMsg);

这是

的输出
<ClientVerificationResult>
   <VerificationIDCheck>NO</VerificationIDCheck>
</ClientVerificationResult>

什么时候应该

<ClientVerificationResult>
   <VerificationIDCheck>YES</VerificationIDCheck>
</ClientVerificationResult>

我猜问题是"$2".matches("Y")返回false。我曾尝试在"$2".equals("Y"); matches()"[Y]"内进行"([Y])"和奇怪的组合,但仍然没有。

如果我打印"$2",则输出为Y。关于我做错了什么的暗示?

2 个答案:

答案 0 :(得分:4)

您不能将Java代码用作replaceAll的替换参数,它应该只是一个字符串。更好地使用PatternMatcher API,并评估matcher.group(2)替换逻辑。

建议代码:

String msg ="    <ClientVerificationResult>\n " +
        "      <VerificationIDCheck>Y</VerificationIDCheck>\n" +
        "    </ClientVerificationResult>\n";

String regex = "(<VerificationIDCheck>)([YN])(</VerificationIDCheck>)";
Pattern p = Pattern.compile(regex);

Matcher m = p.matcher( msg );
StringBuffer sb = new StringBuffer();
while (m.find()) {
    String repl = m.group(2).matches("Y") ? "YES" : "NO";
    m.appendReplacement(sb, m.group(1) + repl + m.group(3));
}
m.appendTail(sb);
System.out.println(sb); // replaced string

答案 1 :(得分:1)

您正在检查文字字符串&#34; $ 2&#34;看它是否匹配&#34; Y&#34;。这永远不会发生。

相关问题