这是我想要处理的输入。我想提取operation
属性的值:
<h:outputLink value="#" id="temp_solution">
<rich:componentContro
for="panel"
attachTo="temp_solution"
operation="show"
event="onclick"/>
</h:outputLink>
在online regex tester的帮助下,我提出了以下正则表达式
(?<=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
请给我一些建议。