我有这个工作正则表达式:^(.*?)}
它用于查找两个大括号之间的值,例如:
[{test},{test2}] // should only find [{test}
但在 java 中这是行不通的:
String regExpression = Pattern.quote("^(.*?)}");
Pattern one = Pattern.compile(regExpression);
Matcher matcherone = one.matcher("[{test},{test2}]");
while (matcherone.find()) {
Text = matcherone.group();
}
最佳答案
转义大括号并删除Pattern.quote
:
String regExpression = "^(.*?)\\}";
Pattern one = Pattern.compile(regExpression);
Matcher matcherone = one.matcher("[{test},{test2}]");
String Text = "";
if (matcherone.find()) {
Text = matcherone.group();
}
System.out.println(Text);
参见 IDEONE demo
matcherone.group();
将匹配 [{test}
,而 group(1)
将返回 [{测试
。
请注意,Pattern.quote("^(.*?)}")
将在所有特殊的正则表达式元字符之前添加转义,这将完全破坏正则表达式模式。
关于模式的注意事项:要匹配 {...}
中的所有子字符串,您可以使用
Pattern one = "\\{([^{}]*)\\}";
并使用 .group(1)
获取它们。
关于java - 工作正则表达式在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36545762/