2013-07-19 36 views
5

我需要一個.net(C#)正則表達式匹配一個逗號分隔的數字列表,如果有一個逗號作爲最後一個字符正則表達式與沒有逗號就結束匹配逗號分隔的列表

123,123,123,123 true - correct match 
123,123,123,123, false - comma on end 
123,123,123,,123 false - double comma 
,123,123,123,123 false - comma at start 
"" false - empty string 

123 true - single value 
不會匹配

我已經找到了這個正則表達式,但匹配結束時有逗號^([0-9]+,?)+$

什麼是適合此模式的正則表達式模式?

編輯:爲清楚起見新增1例正確的答案適用於123

回答

12

嘗試使用這種模式:

^([0-9]+,)*[0-9]+$ 

您可以測試它here

3

試試這個:

//This regex was provided before the question was edited to say that 
//a single number is valid. 
^((\d+\s*,\s*)+(\s*)(\d+))$ 

//In case a single number is valid 
^(\d+)(\s*)(,\s*\d+)*$ 

以下是測試結果

123,123,123,123 match 
123,123,123,123, no match 
123,123,123,,123 no match 
,123,123,123,123 no match 
""     no match (empty string) 
123    no match for the first regex, match for the second one 

Regex doesn't give me expected result

編輯:修改正則表達式,包括單號的最後情況下,沒有任何逗號。

+0

工作在我的情況....感謝您的正確解決方案:) –

1

請試試這個

沒有後綴/前綴逗號:[0-9]+(,[0-9]+)*

無前綴(可選後綴):[0-9]+(,[0-9]+)*,?

無後綴(可選前綴):,?[0-9]+(,[0-9])*

可選後綴和前綴:,?[0-9]+(,[0-9]+)*,?

相關問題