[英]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
请给我一些建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.