如何在java中正确地逃避这个正则表达式模式?

ifl*_*oop 2 java regex

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

<h:outputLink value="#" id="temp_solution">
    <rich:componentContro
        for="panel"
        attachTo="temp_solution"
        operation="show"
        event="onclick"/>
</h:outputLink>
Run Code Online (Sandbox Code Playgroud)

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

(?<=operation=")(\w+)(?=")
Run Code Online (Sandbox Code Playgroud)

为了更有活力,我替换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");
  }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Regex: (?<=operation=")(\w+)(?=")
Nothing found
Run Code Online (Sandbox Code Playgroud)



甚至双重逃避我的代码中的正则表达式:

private static final String REGEX_TEMPLATE = "(?<=%s=\\\")(\\\\w+)(?=\\\")";
Run Code Online (Sandbox Code Playgroud)

无济于事:

Regex: (?<=operation=\")(\\w+)(?=\")
Nothing found
Run Code Online (Sandbox Code Playgroud)

请给我一些建议.

Kep*_*pil 5

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

System.out.println(matcher.find() ? matcher.group(0) : "Nothing found");
Run Code Online (Sandbox Code Playgroud)