Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I verify that a string is in English?

I read a string from the console. How do I make sure it only contains English characters and digits?

like image 443
basvas Avatar asked Feb 15 '10 13:02

basvas


People also ask

How do I check if a string contains only English letters?

String. matches() with argument as "[a-zA-Z]+" returns a boolean value of true if the String contains only alphabets, else it returns false.

How do you check if a string has any characters?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.


1 Answers

Assuming that by "English characters" you are simply referring to the 26-character Latin alphabet, this would be an area where I would use regular expressions: ^[a-zA-Z0-9 ]*$

For example:

if( Regex.IsMatch(Console.ReadLine(), "^[a-zA-Z0-9]*$") ) { /* your code */ } 

The benefit of regular expressions in this case is that all you really care about is whether or not a string matches a pattern - this is one where regular expressions work wonderfully. It clearly captures your intent, and it's easy to extend if you definition of "English characters" expands beyond just the 26 alphabetic ones.

There's a decent series of articles here that teach more about regular expressions.

Jørn Schou-Rode's answer provides a great explanation of how the regular expression presented here works to match your input.

like image 175
LBushkin Avatar answered Oct 05 '22 16:10

LBushkin