[英]Check if a string has only blank spaces or zeros with C#
我想檢測IBAN
帳戶是否所有數字都zero
0
,例如
00 0000 000 00 0000000000
。
所以我建立了這個正則表達式模式來檢查它:
^(0\\s){0,25}$
參數為:檢查輸入字符串是否只有空格或零。
但這是行不通的。 有什么幫助嗎? 謝謝。
這是一個非正則表達式示例。
string input = "00 0000 000 00 0000000000";
bool isNotAllZeros = input
.Where(x => char.IsDigit(x))
.Any(x => x != '0');
它說:“從字符串中獲取所有數字,然后查看是否有一些不為'0'的數字。”
使用All
另一種方法(避免出現雙重否定),在閱讀時可能更有意義:
bool isAllZeros = input
.Where(x => char.IsDigit(x))
.All(x => x == '0');
這表示“輸入'0'中的所有數字都是嗎?”
您可以使用or
運算符|
^(0|\s){0,25}$
或者,您可以使用字符類:
^[0\s]{0,25}$
string input = "00 0000 000 00 0000000000";
bool isAllNum = input.IndexOf(" ") == -1; //true if all are numbers without space
如果要檢查0
或空格,請將0
和空格字符添加到字符類中 。 如果要匹配( \\n
, \\r
, \\t
, \\f
和' '
),請在適當位置使用\\s
。
^[0 ]{0,25}$
解決此問題的一種非常有效的方法是:
string input = "00 0000 000 00 0000000000";
bool isAllZero = input.Any(i => i != ' ' && i != '0');
這將在非空格,非零字符的第一個實例處停止執行。
如果您想保留格式,請嘗試使用此正則表達式,
^[0]{2}\s[0]{4}\s[0]{3}\s[0]{2}\s[0]{10}$
要么
^0{2}\s0{4}\s0{3}\s0{2}\s0{10}$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.