Reputation: 14504
I am trying to validate a 8 digit phone number ex. 12345678
I have created this regexp pattern [0-9]{8}
the only problem is that it also matches a phone number that have more than 8 digits. How do I limit the regex pattern to 8 digits?
Upvotes: 2
Views: 3524
Reputation: 160551
If the string is:
"12345678"
Then it's easy to match eight digits:
/\d{8}/
For instance:
"12345678"[/\d{8}/] # => "12345678"
The problem is, there is nothing in that pattern to tell the engine the string containing the digits must be only eight, so it's happy to match the first eight digits in a string with nine digits too:
"123456789"[/\d{8}/] # => "12345678"
If the number is the only thing in the string, then it's easy to tell the engine it must only find a string consisting of only eight digits, by adding anchors or boundary markers:
"12345678"[/^\d{8}$/] # => "12345678"
"12345678"[/\A\d{8}\z/] # => "12345678"
"12345678"[/\b\d{8}\b/] # => "12345678"
"123456789"[/^\d{8}$/] # => nil
"123456789"[/\A\d{8}\z/] # => nil
"123456789"[/\b\d{8}\b/] # => nil
The first two above work if the string is only eight digits. They fail if the string contains anything else but the eight digits:
" 12345678 "[/^\d{8}$/] # => nil
" 12345678 "[/\A\d{8}\z/] # => nil
To fix that we can use word-boundary markers, which also tell the engine we want only eight digits, without anchoring the search to the start or end of the string:
"12345678"[/\b\d{8}\b/] # => "12345678"
" 12345678 "[/\b\d{8}\b/] # => "12345678"
Upvotes: 1
Reputation: 434665
Say what you mean using anchors:
/\A\d{8}\z/
Note that \A
is beginning of string in Ruby, ^
is beginning of line, similarly for \z
versus $
at the end of the string or line. You almost always want to use \A
and \z
in Ruby or you'll run into problems with embedded newlines.
Upvotes: 8