(?<=#!)(\\w+\\.*\\w+)+ 不匹配 #!super.compound.key3

(?<=#!)(\\w+\\.*\\w+)+ doesn't match #!super.compound.key3

我写了一个简单的正则表达式

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+(?:\.\w+)*

查看 regex demo 和正则表达式图:

Java test:

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.key3]

我想这样写这个正则表达式 (?<=#!)(\\w+\\.?)+.