Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression: single word

Tags:

c#

.net

regex

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?!

like image 378
Elmex Avatar asked Oct 10 '11 13:10

Elmex


People also ask

How do I find a specific word in a regular expression?

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.

What is considered a word in regex?

With some variations depending on the engine, regex usually defines a word character as a letter, digit or underscore.

Does regex work with word?

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.

What is ?: In regex?

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.


2 Answers

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.

like image 61
Sean Bright Avatar answered Oct 18 '22 20:10

Sean Bright


You should add anchors for start and end of string: ^[A-Za-z]+$

like image 5
Sergey Kudriavtsev Avatar answered Oct 18 '22 22:10

Sergey Kudriavtsev