0

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?

user513951
  • 12,445
  • 7
  • 65
  • 82
Haiyuan Zhang
  • 40,802
  • 41
  • 107
  • 134
  • 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 Answers3

2

Use:

/^[-0-9()+x ]+$/

E.g.:

re = /^[-0-9()+x ]+$/
match = re.match("555-555-5555")
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
2
if (/^[-\d()\+x ]+$/.match(variable))
  puts "MATCH"
else
  puts "Does not MATCH"
end
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
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
  • 12,445
  • 7
  • 65
  • 82