tags:

views:

54

answers:

2

I want to validate a string only if it contains '0-9' chars with length between 7 and 9.

What I have is [0-9]{7,9} but this matches a string of ten chars too, which I don't want.

Thanks.

+4  A: 

You'll want to use ^[0-9]{7,9}$.

^ matches the beginning of the string, while $ matches the end.

Michael Madsen
+3  A: 

If you want to find 7-9 digit numbers inside a larger string, you can use a negative lookbehind and lookahead to verify the match isn't preceded or followed by a digit

(?<![0-9])[0-9]{7,9}(?![0-9])

This breaks down as

  • (?<![0-9]) ensure next match is not preceded by a digit
  • [0-9]{7,9} match 7-9 digits as you require
  • (?![0-9]) ensure next char is not a digit

If you simply want to ensure the entire string is a 7-9 digit number, anchor the match to the start and end with ^ and $

^[0-9]{7,9}$
Paul Dixon