[英]Using RegEx to ignore empty strings and spaces
我有以下簡單的測試,由於某種原因沒有返回 true。
string[] test = new string[] { "A", " ", " ", "D", "" };
Regex reg = new Regex(@"^[A-Z]\s$");
bool ok = test.All(x => reg.IsMatch(x));
我也嘗試將 \s 放在方括號內,但這也不起作用
我想確保數組中非空或空格的所有字符都與 AZ 匹配。
我意識到我可以在 All 之前執行 Where(x=>.String.IsNullorEmpty(x) && x != " ") 但我認為 Regex 可以處理這種情況
我想你想要:
Regex reg = new Regex(@"^[A-Z\s]*$");
這基本上是說“字符串完全由空格或 AZ 組成”。
如果要強制它為單個字符或為空,只需將其更改為:
Regex reg = new Regex(@"^[A-Z\s]?$");
Enumerable.All<TSource> Method
確定序列的所有元素是否滿足條件。
正則表達式^[AZ]\s$
表示:雙字符字符串,其第一個字符為AZ
,第二個字符為空格。 你真正想要的是^[AZ\s]*$
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.