繁体   English   中英

如何在Java中正确转义此正则表达式模式?

[英]How to properly escape this regex patterns in java?

这是我要处理的输入。 我想提取operation属性的值:

<h:outputLink value="#" id="temp_solution">
    <rich:componentContro
        for="panel"
        attachTo="temp_solution"
        operation="show"
        event="onclick"/>
</h:outputLink>

在线正则表达式测试器的帮助下,我想到了以下正则表达式

(?<=operation=")(\w+)(?=")

为了更加动态,我将operation替换为%s以便可以在不同情况下使用此模板。 但是,在尝试通过一个小型测试程序来测试我的“创作”时,我遇到了一个问题:

public class Main {
  private static final String INPUT = "<h:outputLink value=\"#\" id=\"temp_solution\">\n"
      + "    <rich:componentControl \n"
      + "        for=\"panel\" \n"
      + "        attachTo=\"temp_solution\" \n"
      + "        operation=\"show\""
      + "        event=\"onclick\"/>  \n"
      + "</h:outputLink>";

  private static final String REGEX_TEMPLATE = "(?<=%s=\")(\\w+)(?=\")";

  public static void main(String[] args) throws IOException {
    final String  actualRegex = String.format(REGEX_TEMPLATE, "operation");    
    final Pattern pattern     = Pattern.compile(actualRegex);
    final Matcher matcher     = pattern.matcher(INPUT);

    System.out.println("Regex: " + pattern);     
    System.out.println(matcher.matches() ? matcher.group(0) : "Nothing found");
  }
}

输出:

Regex: (?<=operation=")(\w+)(?=")
Nothing found



甚至在我的代码中两次转义了正则表达式:

private static final String REGEX_TEMPLATE = "(?<=%s=\\\")(\\\\w+)(?=\\\")";

没有帮助:

Regex: (?<=operation=\")(\\w+)(?=\")
Nothing found

请给我一些建议。

您的正则表达式没有问题。 但是,它与整个输入不匹配,因此不能使用matches() 将其更改为find() ,它仅尝试查找匹配的子序列:

System.out.println(matcher.find() ? matcher.group(0) : "Nothing found");

试试这样的正则表达式:

(?<=operation=\")(\w+)

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM