Share via


Check if a string contains a letter

Question

Monday, July 16, 2012 6:03 AM | 1 vote

Hi.

I would like to know if it is possible to know if a string contains a letter without iterating thru the characters of the string?

Can Regular expressions work? Please show me how, thanks!

Example:

A1234567 ->  contains a letter

S1234567 ->  contains a letter

123B4567 -> contains a letter

12345678 -> doesn't contain a letter

Again, no looping please. :-)

Always remember to say "Thanks" and do necessary actions to show your appreciation. Thanks!

All replies (4)

Monday, July 16, 2012 6:15 AM âś…Answered | 2 votes

You can do it with a Regular Expression:

using System.Text.RegularExpressions;

...

bool containsLetter=Regex.IsMatch(myString, "[A-Z]");

You can also use "[a-zA-Z]" if you want to search for both lowercase and uppercase letters.


Monday, July 16, 2012 6:28 AM | 1 vote

You can do it with a Regular Expression:

using System.Text.RegularExpressions;

...

bool containsLetter=Regex.IsMatch(myString, "[A-Z]");

You can also use "[a-zA-Z]" if you want to search for both lowercase and uppercase letters.

im using "^[a-zA-Z]+$" in regex, whats the difference? Because when i test it, it always returns false unless all the strings are letter.

Always remember to say "Thanks" and do necessary actions to show your appreciation. Thanks!


Monday, July 16, 2012 6:55 AM | 2 votes

The ^and $ mean "Anchor to the beginning and end of the string that is being tested". Therefore, the whole of the tested string would have to match your expression, while the expression that I provided only needs to be found somewhere in the middle of the string.

Also notice the "+" symbol in your expression after the [a-zA-Z]. This means "one or more letters". Since you are anchoring to the beginning and end, your expression mathches all strings that are made of one or more letters, and nothing else except for letters. Therefore, it returns false when you feed it something lile "123B4567".


Monday, July 16, 2012 7:01 AM | 2 votes

try following code

 bool Validate(string inputText)
        {
            return inputText.All(Char.IsLetter);
        }

Mark Answered, if it solves your question and Vote if you found it helpful.
Rohit Arora