0

I have a written a Regex to check whether the string consists of 9 digits or not as follows but this always returning me false even if I have my string as 123456789.

if (Regex.IsMatch(strSSN, " ^\\d{9}$"))

Can any one tell what's wrong and also if any better one provide me .. What i am achieving is the string should have only numeric data and the length should be =9

4 Answers 4

5

Spaces are significant in regular expressions (and of course, you can't match a space character before the start of the string). Remove it and everything should be fine:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

Also, you generally want to use verbatim strings for regexes in C#, so you don't have to double your backslashes, but this is just a convenience, not the reason for your problem:

if (Regex.IsMatch(strSSN, @"^\d{9}$"))
Sign up to request clarification or add additional context in comments.

Comments

0

this should work

^\d{9}$

hope that helps

Comments

0

You have a whitespace between " and ^. It should be:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

Comments

0

could it be the space at the beginning of your pattern? That seems wierd, a space then a number anchored to the start of the line.

This should give you what you want:

if (Regex.IsMatch(strSSN, "^\\d{9}$"))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.