2

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 work 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

3
  • 1
    In .Net 4 you also have String.IsNullOrWhiteSpace which removes the need for && x != " ". Can't help with regex though, sorry (I suck at it) Commented Jul 5, 2011 at 16:17
  • 1
    Please try to be clear about where you mean strings, and where you mean characters: "All characters in the array that are not empty strings" - characters and strings aren't the same thing. Commented Jul 5, 2011 at 16:19
  • 1
    @Jon: It's still not clear what you mean, because you've got an array of strings. I think it would really help if you could reduce your example to matching a single string. Once you've worked out how to get a single string to work how you want, you can move on to match multiple strings with All trivially. Commented Jul 5, 2011 at 16:22

3 Answers 3

5

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]?$");
Sign up to request clarification or add additional context in comments.

7 Comments

Do you mean it will ignore the whitespace ie/it wont try and match against those elements
@Jon: I don't know what you mean. It won't ignore the whitespace - it'll match the whitespace. So "A B C" will match the first regex, as will "A ", but "A0" won't.
I think I need to do the Where clause to strip the whitespace and empties because the All will run over every element
@Jon: It's still not clear what you're trying to do. The first regular expression will match whitespace and empty strings too, so you don't need to strip them out first.
@Jon-not-Skeet: If you add the line Console.WriteLine(ok); to the code in your question, then using either of the regexes in this answer, the output is True. Isn't that what you want?
|
1

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

1 Comment

Yup I think I need the Where clause!
0

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]*$.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.