2013-05-09 32 views
0

正如主題所示,我需要JavaScript正則表達式X個字符長,它接受字母數字字符,但不包含下劃線字符,也接受句點,但不是在開始或結束。期間也不能連續。正則表達式X字符長,字母數字但不是_和句點,但不在開頭或結尾

我幾乎可以到達想要搜索和閱讀其他人的問題以及Stack Overflow(such as here)上的答案。

但是,在我的情況下,我需要一個字符串必須是X字符長(如6),並且可以包含字母和數字(不區分大小寫),也可以包含句點。

說期間不能連續,也不能開始或結束字符串。

Jd.1.4有效,但Jdf1.4f不是(7個字符)。

/^(?:[a-z\d]+(?:\.(?!$))?)+$/i 

是我已經能夠使用其他人的例子來構造,但我不能讓它只接受匹配設定長度的字符串。

/^((?:[a-z\d]+(?:\.(?!$))?)+){6}$/i 

工作,它現在可以接受沒有少於6個字符,但它也愉快地不再接受任何東西,以及...

我明顯失去了一些東西,但我不知道它是什麼。

任何人都可以幫忙嗎?

+3

單獨檢查長度會不會更容易(比如foo.length == 6)? – 2013-05-09 19:02:16

+1

試試這個正則表達式:'/^[az \ d](?![^。] * [。] {2})[az \ d。] {4} [az \ d] $/i' – anubhava 2013-05-09 19:13:54

回答

4

這應該工作:

/^(?!.*?\.\.)[a-z\d][a-z\d.]{4}[a-z\d]$/i 

說明:

^    // matches the beginning of the string 
(?!.*?\.\.) // negative lookahead, only matches if there are no 
       // consecutive periods (.) 
[a-z\d]  // matches a-z and any digit 
[a-z\d.]{4} // matches 4 consecutive characters or digits or periods 
[a-z\d]  // matches a-z and any digit 
$    // matches the end of the string 
+0

This accept' j .... f'作爲有效匹配。 [見小提琴](http://jsfiddle.net/XGundam05/kpBab/)。作者說'時期也不能連續。' – XGundam05 2013-05-09 19:12:27

+0

對吧......讓我想一想。 *編輯:*混淆lookhead語法。修好了,它應該現在工作。 – 2013-05-09 19:15:50

+0

這似乎是個竅門。其中一個有意義的事情是_now_。非常感謝! – Magro284 2013-05-09 19:45:00

2

另一種方式來做到這一點:

/(?=.{6}$)^[a-z\d]+(?:\.[a-z\d]+)*$/i 

解釋:

 (?=.{6}$) this lookahead impose the number of characters before 
        the end of the string 
     ^[a-z\d]+ 1 or more alphanumeric characters at the beginning 
        of the string 
(?:\.[a-z\d]+)* 0 or more groups containing a dot followed by 1 or 
        more alphanumerics 
       $ end of the string 
+0

基於一些測試,正則表達式本身殲匹配如果字符串是一樣的東西:J..14a – Magro284 2013-05-09 19:52:23

+0

@ Magro284:更正:我已經忘了最後的$ – 2013-05-09 19:55:43

+0

我喜歡這個解決方案很多。清潔並且對我的思維方式有意義。 – Magro284 2013-05-09 20:15:25

相關問題