开发者

Regular Expression that Matches Any Number or Letter or Dash

Given searchString = "23423asdfa-''"

This regular exp开发者_如何学JAVAression should evaluate to false but it does not! Any ideas?

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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜