2012-10-13 41 views

回答

38

試試這個,它可能工作,

^(?:([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) «$» 
+0

完美,謝謝! – alfasin

+2

@JohnWoo我不知道你用什麼工具生成解釋? – turtledove

+0

@JohnWoo謝謝,很棒的工具! – turtledove

11

您可以檢查是否有字符串中字符的2個實例:

^.*(.).*\1.*$ 

(我只是簡單地捕獲一個字符,並檢查它是否有其他地方的副本與反向引用。 .*的其餘部分不在乎)。

如果上述正則表達式匹配,則該字符串具有重複字符。如果上面的正則表達式不匹配,那麼所有的字符都是唯一的。

上面的正則表達式的好處是當正則表達式引擎不支持環顧四周。

顯然John Woo的解決方案是一種直接檢查唯一性的好方法。它斷言每個字符前面的字符串不會包含當前字符。

+1

簡單而有效。即使看不到錨點也更簡單:'(。)。* \ 1' – pabo

0

這一次也將提供一個完整的匹配任何長度的詞與非重複的字母:

^(?!.*(.).*\1)[a-z]+$ 

我稍微修改了@Bohemian提供的answer到另一個問題,是。

自從上面的問題已經被問了,也已經有一段時間了,但是我認爲在這裏也有這個正則表達式模式會很好。

相關問題