Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check a string contains just one word

Tags:

c#

regex

I was shown the following:

[RegularExpression(@"\b*[a-zA-Z0-9_]\b", ErrorMessage = "Enter a single work account name please")]

But it seems to give an error when a string contains more than one character. Can someone help with a Regex that checks if there is more than one word in a string?

like image 882
Samantha J T Star Avatar asked Dec 16 '11 16:12

Samantha J T Star


2 Answers

^[a-zA-Z0-9_]+$

Word boundaries \b do not work here, as the pattern will match for each word.

If you want to allow non-Latin characters, you can use the shorthand version:

^\w+$
like image 182
Jay Avatar answered Sep 22 '22 15:09

Jay


There was only missing one single piece to your regex

 @"^\b[a-zA-Z0-9_]+\b$"

you forgot to state that the character could be repeated more than 1 time. That's the reason for the plus sign, so that it may accept only 1 word

like image 45
jclozano Avatar answered Sep 26 '22 15:09

jclozano