2014-02-10 104 views

回答

4

你的正則表達式是錯誤的。試試這個:

/^[[email protected]'-]+$/ 

OR

/^[\[email protected]'-]+$/ 

連字符必須在字符類,以避免逃逸內第一個或最後一個位置。此外,如果是不允許的空字符串,則使用+(1或多個),而不是*(0或更多)

說明:

^ assert position at start of the string 
[\[email protected]'-]+ match a single character present in the list below 
Quantifier: Between one and unlimited times, as many times as possible 
\w match any word character [a-zA-Z0-9_] 
@'- a single character in the list @'- literally 
$ assert position at end of the string 
+0

除此之外,如果我想接受數字和@也。 – swati

+0

當然,檢查更新的答案。 – anubhava

+1

謝謝,它的工作就像一個魅力。我會很感激,如果你提供相同的解釋 – swati

3

移動在末端連字符或的所述beginig字符類或逃避它:

^[ A-Za-z_'-]*$ 

^[- A-Za-z_']*$ 

^[ A-Za-z\-_']*$ 

如果你希望所有的信件:

^[ \pL_'-]*$ 

+0

+1引入的[Unicode屬性'\ pL'(http://www.regular-expressions.info/unicode.html#prop)! – stema

+0

@stema:謝謝。 – Toto

0

當使用字符類一個連字符,請務必將其放置在字符類的結尾作爲最佳實踐。

原因是因爲連字符用於表示字符類中字符的範圍,並且當它位於類的末尾時,它不會創建任何範圍。

0

您可以使用以下(在Java中):

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((['_-]+)\\p{Alpha})?)*+$"; 

如果你想擁有的空間和@同時(如一些人上面給出)嘗試:

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((\\s|['@_-]+)\\p{Alpha})?)*+$";