Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression that Matches Any Number or Letter or Dash

Tags:

c#

.net

regex

Given searchString = "23423asdfa-''"

This regular expression should evaluate to false but it does not! Any ideas?

Regex rgx = new Regex(@"[\w-]*");
rgx.IsMatch(searchString)
like image 918
Arizona1911 Avatar asked Aug 05 '10 15:08

Arizona1911


2 Answers

It's because you haven't constrained it to match the entire string. Hence it is allowed to consider matches on subsets of the string. A very large subset of the string matches the data hence the regex returns true.

Try the following to force it to match the entire input.

Regex rgx = new Regex(@"^[\w-]*$");
rgx.IsMatch(searchString)
like image 150
JaredPar Avatar answered Sep 19 '22 22:09

JaredPar


You need to anchor your expression. If you don't, then if any substring of the input matches, the regex match is considered successful. Change the regex to "^[\w-]*$" where the ^ and $ will match the beginning and end of the string, respectively.

like image 32
siride Avatar answered Sep 18 '22 22:09

siride