Regex Non-Duplicate Bigrams

荒凉一梦 提交于 2019-12-06 15:27:30

问题


I want a PCRE regex to create bigram pairings similar to this question, but without duplicates words.

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

The closest I’ve gotten to it is this, but ‘orange’ isn’t captured in the second group.

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

回答1:


You're looking for this:

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

Here's a quick perl one-liner to demonstrate it:

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

This uses a zero-width lookahead (?=…) around the capture group to ensure we can read the word "orange" twice.

If we used /(\b\w+\s+\w+)/g instead, we'd get "apple orange" but not the second match because the left-to-right processing of the regular expression would have already passed over the word "orange"

If we omit the word break \b, the regex interpreter would give us "apple orange" and then "pple orange", "ple orange", etc ... including "orange plum" later on, but also "range plum" through "e plum" since those all satisfy that criteria.

Full explanation of my original regex at Regex101



来源:https://stackoverflow.com/questions/54279023/regex-non-duplicate-bigrams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!