I want to check in a C# program, if a user input is a single word. The word my only have characters A-Z and a-z. No spaces or other characters.
I try [A-Za-z]*
, but this doesn't work. What is wrong with this expression?
Regex regex = new Regex("[A-Za-z]*");
if (!regex.IsMatch(userinput);)
{
...
}
Can you recomend website with a comprensiv list of regex examples?!
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
With some variations depending on the engine, regex usually defines a word character as a letter, digit or underscore.
Word supports regex in its own unique way! A regex is a pattern matching a set of text strings. An elementary regex pattern matches a single character, as follows: Any letter, digit and most of the special characters matches itself.
It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.
It probably works, but you aren't anchoring the regular expression. You need to use ^
and $
to anchor the expression to the beginning and end of the string, respectively:
Regex regex = new Regex("^[A-Za-z]+$");
I've also changed *
to +
because *
will match 0 or more times while +
will match 1 or more times.
You should add anchors for start and end of string: ^[A-Za-z]+$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With