开发者

Using RegEx to ignore empty strings and spaces

开发者 https://www.devze.com 2023-03-17 23:41 出处:网络
I have the following simple test which doesnt return true for some reason. string[] test = new string[] { \"A\", \" \", \" \", \"D\", \"\" };

I have the following simple test which doesnt return true for some reason.

string[] test = new string[] { "A", " ", " ", "D", "" };
Regex reg = new Regex(@"^[A-Z]\s$");
bool ok = test.All(x => reg.IsMatch(x));

I've also tried putting the \s inside the square brackets but that doesn't 开发者_如何学Pythonwork either

I want to make sure that all characters in the array that are not empty or blank spaces match A-Z.

I realise I could do a Where(x=>!String.IsNullorEmpty(x) && x != " ") before the All but I thought Regex could handle this scenario


I think you want:

Regex reg = new Regex(@"^[A-Z\s]*$");

That basically says "the string consists entirely of whitespace or A-Z".

If you want to force it to be a single character or empty, just change it to:

Regex reg = new Regex(@"^[A-Z\s]?$");


Enumerable.All<TSource> Method Determines whether all elements of a sequence satisfy a condition.


The regular expression ^[A-Z]\s$ says: two-character string, whose first character is A-Z and the second is a white space. What you actually want is ^[A-Z\s]*$.

0

精彩评论

暂无评论...
验证码 换一张
取 消