正则表达式“或"运算符避免重复 [英] Regex 'or' operator avoid repetition

查看:49
本文介绍了正则表达式“或"运算符避免重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不允许重复的同时使用或运算符?换句话说,正则表达式:

How can I use the or operator while not allowing repetition? In other words the regex:

(word1|word2|word3)+

将匹配 word1word2 ,但也将匹配 word1word1 ,我不希望这样,因为单词word1被重复.如何避免重复?

will match word1word2 but will also match word1word1 which I don't want that because the word word1 is being repeated. How can I avoid repetition?

总而言之,我希望以下主题相匹配:

In summary I will like the following subjects to match:

word1word2word3
word1
word2
word3word2

请注意,所有它们都匹配,因为没有重复.而且,我希望以下学科不及格:

Note all of them match cause there is no repetition. And I will like the following subjects to fail:

word1word2word1
word2word2
word3word1word2word2

编辑

感谢 @Mark 我知道:

(?xi)

(?:  
        (?<A>word1|word2)(?!  .*  \k<A> )      # match for word1 or word2 but make sure that if you capture it it does not follow what it was just captured
    |   (?<B>word3|word4)(?!  .*  \k<B> )
)+

因为我有兴趣查看是否在A组或B组中捕获了某些东西.

because I am interested in seeing if something was captured in group A or B.

推荐答案

您可以使用否定前瞻:

^(?:word1(?!.*word1)|word2(?!.*word2)|word3(?!.*word3))+$

查看其在线运行情况: rubular

See it working online: rubular

这篇关于正则表达式“或"运算符避免重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆