[英]Regex to match comma separated string with no comma at the end of the line
[英]Regex to match comma separated list with no comma on the end
我需要一個.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
試試這個:
//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
編輯:修改正則表達式以包括單個數字的最后一個案例,不帶任何逗號。
請試試這個
沒有后綴/前綴逗號: [0-9]+(,[0-9]+)*
沒有前綴(可選后綴): [0-9]+(,[0-9]+)*,?
沒有后綴(可選前綴): ,?[0-9]+(,[0-9])*
可選的后綴和前綴: ,?[0-9]+(,[0-9]+)*,?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.