nunos
nunos

Reputation: 21389

Validate that string is all digits and has a qualifying length

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.

Upvotes: 0

Views: 106

Answers (2)

Paul Dixon
Paul Dixon

Reputation: 300845

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}$

Upvotes: 3

Michael Madsen
Michael Madsen

Reputation: 55009

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

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

Upvotes: 4

Related Questions