开发者

How can I test whether a string only contains characters in a given set? [duplicate]

开发者 https://www.devze.com 2023-01-31 04:57 出处:网络
This question already has answers here: 开发者_C百科 Validate that string contains only allowed characters in Ruby
This question already has answers here: 开发者_C百科 Validate that string contains only allowed characters in Ruby (4 answers) Closed 2 years ago.

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?


Use:

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

E.g.:

re = /^[-0-9()+x ]+$/
match = re.match("555-555-5555")


if (/^[-\d()\+x ]+$/.match(variable))
  puts "MATCH"
else
  puts "Does not MATCH"
end


Use String#count:

"+1 (800) 123-4567".count("^0-9+x()\\- ").zero?  # => true
"x invalid string x".count("^0-9+x()\\- ").zero? # => false
0

精彩评论

暂无评论...
验证码 换一张
取 消