2015-01-06 93 views
2

我有我需要驗證的輸入形式的列表,該列表必須遵循這些規則正則表達式以允許逗號分隔碼

  • 逗號分隔
  • 每個代碼可以
    • 開始單個字母,隨後僅由單個下劃線,隨後任意數量的字母或
    • 一組數字
  • 列表不能以尾隨逗號結束

有效示例數據

  • A_AAAAA,B_BBBBB,122334,D_DFDFDF
  • 12345,123567,123456,A_BBBBB,C_DDDDD,1234567

示例數據無效

  • RR_RRR,12345
  • 1_111,AVSFFF,
  • A_SDDF ,, 123342

我使用http://www.regexr.com而據已經得到就象這樣:[AZ _] _ [AZ] ,| [0-9]

與此問題是在每個有效數據示例中的最後的代碼沒有被選擇,因此線不通過正則表達式模式

回答

1

試試這個:

​​

regex101 demo.


說明:

^ start of string 
(?: this group matches a single element in the list: 
    (?: 
     [A-Za-z] a character 
     _   underscore 
     [A-Za-z]* any number of characters (including 0) 
    | or 
     \d+ digits 
    ) 
    (?: followed by either a comma 
     , 
    | or the end of the string 
     $ 
    ) 
)+ match any number of list elements 
(?<! make sure there's no trailing comma 
    , 
) 
$ end of string 
+0

謝謝你,真的很清楚的解釋和它的效果很好 – user2847098

+1

@ user2847098:'該列表不能以尾隨逗號結束此解決方案允許列表以尾隨逗號結尾 – nhahtdh

+0

@nhahtdh:答案已更新。 –

1

嘗試此 -

^(?:[A-Z]_[A-Z]*|[0-9]+)(?:,(?:[A-Z]_[A-Z]*|[0-9]+))*$ 

Demo

+1

注意'(令牌分離器)* token'比'效率較低令牌(分隔符令牌)*'。如果引擎未能匹配下一個「令牌分隔符」,它會在回溯一次重複之前嘗試使用「令牌」。查看regex101上這兩個示例的「正則表達式調試器」部分:https://regex101.com/r/zC0xH2/1 https://regex101.com/r/dU7mR3/1 – nhahtdh

+0

@nhahtdh酷,這是有道理的。我以前的正則表達式需要103步來匹配,而新的步驟需要83步。更新了答案。謝謝:) – Kamehameha

相關問題