2016-03-08 78 views
0

我希望能夠以匹配這些類型字符串(逗號分隔,並沒有開始或尾部空格):JS正則表達式先行

LaunchTool [0] .Label,LaunchTool [0] .URI,LaunchTool [1] .Label,LaunchTool [1] .URI,LaunchItg [0] .Label,LaunchItg [0] .URI,csr_description

的規則,在英國,有:

1) Zero or more instances of [] where the brackets must contain only one number 0-9 
2) Zero or more instances of ., where . must be followed by a letter 
3) Zero or more instances of _, where _ must be followed by a letter 

我目前有這個正則表達式:

/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i 

我想不通爲什麼

"aaaa"不匹配

furthemore,

"aaaa[0].a"比賽,但"aaaa[0]"不...

人知道什麼是錯的?我相信我可能需要一個前瞻來確定。 _字符後面跟着一個字母?也許我可以避免它。

回答

1
  1. 此正則表達式可以匹配 「AAAA」,嘗試的

(/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i).test("aaaa")

獲得值
  • 「AAAA [0]」 不匹配,因爲有在表達式結尾處是[a-z]{1,}。一旦「[0]」與(\[[0-9]\]){0,}匹配,尾部[a-z]{1,}必須顯示在字符串末尾
  • +0

    並嘗試使用'*'/'+'。這是很方便的方式來表達'{0,}'/'{1,}' –

    +0

    謝謝,我剛剛學習JS正則表達式,並且我首先發現{}符號更容易,因爲我不記得快捷鍵 –

    +0

    沒有在線測試表示「aaa」或任何簡單的字符串都與此正則表達式匹配 –

    0

    使用可選捕獲組。例如:([a-z])?

    這裏是我結束了: /^((\w+)(\[\d+\])?\.?(\w+)?,?)+$/

    速記解釋:

    * = {0,} 
    + = {1,} 
    \w = [A-Za-z0-9_] 
    \d = [0-9]