【问题标题】:Regex Non-Duplicate Bigrams正则表达式非重复二元组
【发布时间】:2019-01-20 17:25:18
【问题描述】:

我想要一个 PCRE 正则表达式来创建类似于 question 的二元组配对,但没有重复的单词。

Full Match: apple orange plum
Group 1: apple orange
Group 2: orange plum

我最接近它的是这个,但是第二组中没有捕获到“橙色”。

(\b.+\b)(\g<1>)\b

【问题讨论】:

  • “类似这个问题”?什么问题?
  • 道歉已修复。
  • 你想要像(?=(\w+\s+\w+))这样的东西

标签: regex pcre regex-group


【解决方案1】:

你正在寻找这个:

/(?=(\b\w+\s+\w+))/g

这里有一个快速的 perl 单行代码来演示它:

$ perl -e 'while ("apple orange plum" =~ /(?=(\b\w+\s+\w+))/g) { print "$1\n" }'
apple orange
orange plum

这在捕获组周围使用零宽度lookahead(?=…),以确保我们可以读取“橙色”一词两次。

如果我们改用/(\b\w+\s+\w+)/g,我们会得到“apple orange”,但不会得到第二个匹配项,因为正则表达式的从左到右处理已经超过了单词“orange”

如果我们省略break \b这个词,正则表达式解释器会给我们“apple orange”,然后是“pple orange”,“ple orange”等...包括“orange plum”,但也有“从“plum”到“e plum”,因为它们都满足该标准。

Full explanation of my original regex at Regex101

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多