簡體   English   中英

有沒有辦法找出C#中的字符串是否不包含數字和字符0-9和AZ?

[英]Is there a way I can find out if a string in C# does not contain the numbers & characters 0-9 and A-Z?

我已經看過某種正則表達式測試,但是如何檢查字符串是否不包含任何0-9數字或AZ字符?

您不需要正則表達式:

string s = ...
bool hasLetterOrDigit = s.Any(c => char.IsLetterOrDigit(c));

bool onlyLetterOrDigit = s.All(c => char.IsLetterOrDigit(c));

IsLetterOrDigit()函數使用Unicode分類( MSDN )。

如果要精確控制:

string s = ...
string allowedChars = "abcdefABCDEF0123456789";

bool onlyAllowedChar = s.All(c => allowedChars.Contains(c));

使用正則表達式嘗試

bool Exists=Regex.IsMatch(input, @"[^A-Z0-9]+");

就像是...

if ((Regex.IsMatch(value, "[^A-Z0-9]+")
{
   //do something
}

編輯:更改為匹配Matt的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM