是否可以使用正则表达式查找单词序列?

时间:2016-11-24 17:01:10

标签: regex

是否可以找到一个单词的结束字母与下一个单词的开头字母相同的序列,并且该单词的结束字母与下一个单词的开头字母相同,依此类推?

例如:

elementum magna sodales应该与elementum magna匹配,而Proin nunc curna, aliquet nec之类的内容应该返回Proin nunc curna, aliquet,但an earring应该不返回任何内容,因为n不是与e相同。

我尝试了类似\w*(\w)[\s:;'",.?!]*\1\w*的内容,但只匹配两个单词,我需要它们一起菊花链。

2 个答案:

答案 0 :(得分:4)

您可以使用此模式执行此操作:

(?i)\b(?:[a-z]*([a-z])[^a-z]+(?=\1))+[a-z]*

详细说明:

(?i) # makes the pattern case-insensitive
\b
(?:  # non-capturing group: one word and eventual following non-word characters
    [a-z]*([a-z]) # a word with the capture of the last character
    [^a-z]+ # non-word characters
    (?=\1) # lookahead that checks the next word first letter
)+ # repeat
[a-z]* # last next word

demo

答案 1 :(得分:0)

是的,理论上如果你的正则表达式引擎支持recursive references

这个问题类似于检查字符串是否为回文(问题:How to check that a string is a palindrome using regular expressions?)。