我正在尋找一個正則表達式匹配一個單詞,只有當它的所有字符都是唯一的,這意味着該單詞中的每個字符只出現一次。正則表達式匹配一個單詞與獨特(非重複)字符
例:
abcdefg
- >將返回MATCH
abcdefgbh
- >將返回敵不過(因爲字母b
重複一次以上)
我正在尋找一個正則表達式匹配一個單詞,只有當它的所有字符都是唯一的,這意味着該單詞中的每個字符只出現一次。正則表達式匹配一個單詞與獨特(非重複)字符
例:
abcdefg
- >將返回MATCH
abcdefgbh
- >將返回敵不過(因爲字母b
重複一次以上)
試試這個,它可能工作,
^(?:([A-Za-z])(?!.*\1))*$
說明
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) «$»
您可以檢查是否有字符串中字符的2個實例:
^.*(.).*\1.*$
(我只是簡單地捕獲一個字符,並檢查它是否有其他地方的副本與反向引用。 .*
的其餘部分不在乎)。
如果上述正則表達式匹配,則該字符串具有重複字符。如果上面的正則表達式不匹配,那麼所有的字符都是唯一的。
上面的正則表達式的好處是當正則表達式引擎不支持環顧四周。
顯然John Woo的解決方案是一種直接檢查唯一性的好方法。它斷言每個字符前面的字符串不會包含當前字符。
簡單而有效。即使看不到錨點也更簡單:'(。)。* \ 1' – pabo
這一次也將提供一個完整的匹配任何長度的詞與非重複的字母:
^(?!.*(.).*\1)[a-z]+$
我稍微修改了@Bohemian提供的answer到另一個問題,是。
自從上面的問題已經被問了,也已經有一段時間了,但是我認爲在這裏也有這個正則表達式模式會很好。
完美,謝謝! – alfasin
@JohnWoo我不知道你用什麼工具生成解釋? – turtledove
@JohnWoo謝謝,很棒的工具! – turtledove