我正在尝试使用 java 正则表达式来匹配特定的字符串模式。
我想找到类似的模式
{some stuff|other stuff}
我使用以下模式:
"(\\{#" + key + ")(\\|.*)[^\\}]"
问题是当我遇到类似的情况时:
text... {some stuff|other stuff} {some stuff|other stuff} more text
我正在匹配 {some stuff|other stuff} {some stuff|other stuff}
,而不是 2 次出现的 {some stuff|other stuff}。
我认为这在某种程度上与正则表达式回溯有关,但我不知道如何解决它。
有什么想法吗?
我的Java代码:
Pattern pattern = Pattern.compile("(\\{#" + key + ")(\\|.*)[^\\}]");
Matcher m = pattern.matcher(string);
while (m.find()) {
logger.info(m.group(0));
//logger.warn("Parameter " + key + " is not found");
// throw new Exception("Parameter " + key + " is not found");
}
最佳答案
您可以使用string.matches("({"+key.replace('.',"\\.").replace('|',"\\|")+"|(.*)})+")
。
关于java - 正则表达式同一行匹配的相同字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40079803/