如何测试字符串是否只包含给定集合中的字符?
给定一个移动电话号码的字符串,我需要确保给定的字符串只包含数字0-9
, (
, )
, +
, -
, x
和空格。 我怎么能在Ruby中做到这一点?
使用:
/^[-0-9()+x ]+$/
例如:
re = /^[-0-9()+x ]+$/ match = re.match("555-555-5555")
if (/^[-\d()\+x ]+$/.match(variable)) puts "MATCH" else puts "Does not MATCH" end
使用字符串#count :
"+1 (800) 123-4567".count("^0-9+x()\\- ").zero? # => true "x invalid string x".count("^0-9+x()\\- ").zero? # => false