【发布时间】:2019-08-20 07:16:38
【问题描述】:
我写了一个简单的正则表达式
String s = "#!key1 #!compound.key2 #!super.compound.key3";
Matcher matcher = Pattern.compile("(?<=#!)(\\w+\\.*\\w+)+").matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
导致
实际
key1
compound.key2
super.compound
我想知道为什么它匹配super.compound,而不是我预期的super.compound.key3。
预期
key1
compound.key2
super.compound.key3
欢迎对正则表达式进行任何改进。
【问题讨论】:
-
它不匹配,因为您的量化集群在每次迭代开始时寻找
\w,而不是.。因此,当它匹配super.compound时,它不能匹配下一个.,因为它需要\w。将您的正则表达式更改为(?<=#!)(?:\\w+\\.?)+。
标签: java regex lookbehind