Matthew Layton
Matthew Layton

Reputation: 42260

Why does this Regex match?

I have written a regular expression to match the following criteria

([0-9\-\w]{10,25})

I am using it to detect payment card numbers, so this works:

Regex.IsMatch("34343434343434", "([0-9\\-\\w]{10,25})"); // true

But this also works:

Regex.IsMatch("LogMethodComplete", "([0-9\\-\\w]{10,25})"); // true

What am I doing wrong?

This is C#

Upvotes: 1

Views: 59

Answers (2)

sloth
sloth

Reputation: 101072

Take a look at Regular Expression Language - Quick Reference, section Character Classes.

\w matches any word character including underscore, not whitespace.

To match whitespace, you can use \s.

To match digits, you can use \d.

Upvotes: 8

Robert
Robert

Reputation: 20286

Instead of using \w you can use \d which means digit you could use regex like

"[\d\-\s]{10,25}" to match your criteria

You don't need to check for "words" and this is what \w does

Upvotes: 2

Related Questions