0

I have written a RegEx for password which takes any character with min length of 5 and maximum length of 30.

I've tried the following expression:

(\S){5,30}

but it also accepts passwords with more than 30 characters. How can I make sure it doesn't match such passwords?

3
  • 8
    Show sample input and explain what isn't matched that you expect to be matched. Saying something is "not working" is very vague - you need to be much more explicit. Commented Sep 20, 2011 at 12:32
  • I tried an input password which is more than 30 characters and it is not validating correctly. Commented Sep 20, 2011 at 12:38
  • 3
    You might want to anchor that RE… Commented Sep 20, 2011 at 12:40

2 Answers 2

6

Your problem is that your regex also matches substrings of your input.

\S{5} (or (\S){5}) matches 12345 in the string 1234567890.

So you need to anchor your regex:

^\S{5,30}$

validates a 5-30 character, non-whitespace string. The parentheses around \S are useless and unnecessary.

At any rate, why would you impose a length restriction on a password? And why wouldn't you allow whitespace characters in it? See also this.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for the anchors, but I don't think thats the problem why its not working for the OP.
@stema: Why not? He's using Regex.IsMatch() as mentioned in one of the comments. I'm willing to bet all rep points I earned today that missing anchors are the problem.
OK, I overlooked that comment
+1 for the correct answer, a good explanation, mentioning that the parentheses are unnecessary, and pointing out that password restrictions aren't a good idea. Wish I could give you more than +1 for this.
0

If you really want "any character" use the period (.) instead of \S.

4 Comments

He wants to match strings without spaces in them. "." will catch those.
Perhaps, but he did say "any character" and did not specify non-whitespace in the description (though implied with the "\S"). In general, passwords could accept spaces.
@Box: You're right. +1 for this (even though it's peripheral to the problem).
This should really be a comment. It doesn't address the OP's problem, it only clarifies some minor semantics of the question. The choice of \S instead of . was quite possibly intentional, even if blocking whitespace in passwords is a bad idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.