Regex Non-Duplicate Bigrams

浪尽此生 提交于 2019-12-04 21:14:01

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

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