Given a string of a mobile phone number, I need to make sure that the given string only contains digits 0-9, (,),+,-,x, and space. How can I do it in Ruby?
Asked
Active
Viewed 256 times
0
user513951
- 11,572
- 7
- 61
- 75
Haiyuan Zhang
- 38,486
- 40
- 103
- 133
-
Ruby RegEx syntax is borrowed from Perl. As you know regex in Perl, you can use the same here too. – dheerosaur Dec 15 '10 at 09:23
-
A potential problem is that phone number formats vary around the world. Unless you know the region and you did _NOT_ let users enter them by hand, the input could generate false warnings. See https://stackoverflow.com/q/123559/128421 – the Tin Man Feb 14 '20 at 19:34
-
A much more thorough discussion with examples is https://stackoverflow.com/q/123559/128421 – the Tin Man Feb 14 '20 at 20:09
-
Rather than try to reinvent a wheel use an existing wheel: "[telephone_number](https://github.com/mobi/telephone_number)". – the Tin Man Feb 14 '20 at 20:19
3 Answers
2
Use:
/^[-0-9()+x ]+$/
E.g.:
re = /^[-0-9()+x ]+$/
match = re.match("555-555-5555")
Matthew Flaschen
- 268,153
- 48
- 509
- 534
2
if (/^[-\d()\+x ]+$/.match(variable))
puts "MATCH"
else
puts "Does not MATCH"
end
KARASZI István
- 29,989
- 8
- 97
- 120
1
Use String#count:
"+1 (800) 123-4567".count("^0-9+x()\\- ").zero? # => true
"x invalid string x".count("^0-9+x()\\- ").zero? # => false
user513951
- 11,572
- 7
- 61
- 75