正则表达式将单词与唯一(非重复)字符匹配

alf*_*sin 20 regex

我正在寻找一个只有当一个单词的所有字符都是唯一的时才匹配单词的正则表达式,这意味着单词中的每个字符只出现一次.

示例:
abcdefg- >将返回MATCH
abcdefgbh - >将返回NO MATCH(因为该字母b重复多次)

Joh*_*Woo 42

试试这个,它可能会起作用,

^(?:([A-Za-z])(?!.*\1))*$
Run Code Online (Sandbox Code Playgroud)

说明

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below «(?:([A-Z])(?!.*\1))*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Match the regular expression below and capture its match into backreference number 1 «([A-Z])»
      Match a single character in the range between “A” and “Z” «[A-Z]»
   Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*\1)»
      Match any single character that is not a line break character «.*»
         Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      Match the same text as most recently matched by capturing group number 1 «\1»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Run Code Online (Sandbox Code Playgroud)

  • @JohnWoo我想知道你用什么工具来产生解释? (2认同)
  • @turtledove我知道[`expresso`](http://www.ultrapico.com/Expresso.htm)会产生解释 - 但John使用了别的东西. (2认同)

nha*_*tdh 12

您可以检查字符串中是否有2个字符实例:

^.*(.).*\1.*$
Run Code Online (Sandbox Code Playgroud)

(我只是简单地捕获其中一个角色,并检查它是否有其他地方的副本,后面的参考.其余的.*都不关心).

如果上面的正则表达式匹配,那么该字符串具有重复的字符.如果上面的正则表达式不匹配,则所有字符都是唯一的.

上面的正则表达式的好处是当正则表达式引擎不支持环顾四周时.

显然,John Woo的解决方案是一种直接检查唯一性的漂亮方式.它在每个字符处断言前面的字符串不包含当前字符.