tags:

views:

65

answers:

2

Given searchString = "23423asdfa-''"

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

Regex rgx = new Regex(@"[\w-]*");
rgx.IsMatch(searchString)
+8  A: 

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)
JaredPar
Thanks! I knew I was forgetting something really simple.
Arizona1911
+2  A: 

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.

siride