【问题标题】:(?<=#!)(\\w+\\.*\\w+)+ doesn't match #!super.compound.key3(?<=#!)(\\w+\\.*\\w+)+ 不匹配 #!super.compound.key3
【发布时间】: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。将您的正则表达式更改为(?&lt;=#!)(?:\\w+\\.?)+

标签: java regex lookbehind


【解决方案1】:

你需要使用

(?<=#!)\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]

【讨论】:

  • 谢谢,我怎样才能在那里生成正则表达式图?
  • @AndrewTobilko 我使用了jex.im/regulex,但它不支持lookbehinds,我手动编辑了图像。
【解决方案2】:

我想这样写这个正则表达式 (?。

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2016-08-15
    • 1970-01-01
    • 2020-02-19
    • 2013-11-15
    • 2021-02-23
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多