正则表达式检查一组字符是否重复 [英] Regex to check non-repetition of a set of characters
问题描述
假设我有一组字符[ABC]
.我正在寻找一个正则表达式,该正则表达式将匹配超集的任何排列(空集除外),即
Suppose I have the set of characters [ABC]
. I'm looking for a regex that would match any permutation of the superset except the empty set, i.e.
ABC ACB BAC BCA CAB CBA
AB BC AC CB CA BA
A B C
正则表达式应该(显然)不匹配空字符串.
The regex should (obviously) not match the empty string.
p.s.表达相同目标的另一种方法是将包含集合中每个字符的任何非空字符串最多匹配一次".
p.s. An alternative way to express the same objective is "match any non-empty string containing each character in the set at most once".
更新:集合[ABC]
只是一个示例,实际集合也可能更大.带着这个问题,我希望找到一种通用"解决方案,而不是针对[ABC]
的特定解决方案.
update: The set [ABC]
is just an example, for the real set may also be bigger. With this question I was hoping to find a "general" solution rather than a particular one for [ABC]
.
推荐答案
感谢您的回答(尤其是anubhava和codaddict的回答),我能够找到此解决方案,我认为这很优雅,因为它只允许键入一次集:
Thanks to your answers (especially anubhava's and codaddict's) I was able to find this solution, that I think is pretty elegant because it allows to type the set only once:
\b(([ABC])(?!.*\2))+\b
需要
\b
来匹配完整的单词;省略它们还会找到尊重所需属性的子词.要匹配完整的字符串,您显然可以这样做:
the \b
are needed to match full words; omitting them will also find subwords respecting the required property. To match a full string, you'd obviously do:
^(([ABC])(?!.*\2))+$
这篇关于正则表达式检查一组字符是否重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!