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

标签 java regex lookbehind

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

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和正则表达式图:

enter image description here

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]

关于java - (?<=#!)(\\w+\\.*\\w+)+ 与 #!super.compound.key3 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568460/

相关文章:

java - Camel Spring Java 配置 Camel 2.15 与 Camel 2.17

C++ boost 正则表达式日期错误

c# - 识别确切文件名的正则表达式模式

javascript - Lookbehind 在 Chrome 中工作,但在 Safari 中中断 : Invalid regular expression invalid group

java - 要么显示最大小数位数,要么根本不显示

java - 基本 Java 方法执行

regex - 在 BASH 中的字符串末尾前插入一个字符 4 个字符

regex - 可变长度 Lookbehind 在 perl 文件中不起作用,但在单行中起作用

java - 回顾中的反向引用

java - 如何添加用户库作为播放框架的依赖项?