如何验证字符串仅包含零和一个?

时间:2014-03-02 15:17:37

标签: ruby string validation

我有一个字符串,只能由01组成。如果字符串包含任何其他字符(包括特殊字符),则验证应返回false;否则它应该返回一个真实的。

我怎样才能做到这一点?

5 个答案:

答案 0 :(得分:3)

使用Regexp#===

s = '11er0'
# means other character present except 1 and 0
/[^10]/ === s # => true 

s = '1100'
# means other character not present except 1 and 0
/[^10]/ === s # => false

这是一种方法:

def only_1_and_0(s)
  !(/[^10]/ === s)
end

only_1_and_0('11012') # => false
only_1_and_0('1101') # => true

答案 1 :(得分:1)

试试这个:

def only_0_and_1(str)
  return !!(str =~ /^(0|1)+$/)
end

答案 2 :(得分:0)

以下假设您的方法始终会收到一个字符串;它不执行任何强制或类型检查。如果您需要,请随意添加。

def binary? str
  ! str.scan(/[^01]/).any?
end

这将使用String#scan扫描字符串中除0或1以外的任何字符,然后返回反转的布尔值,如果Enumerable#any?为真,则计算结果为false,表示其他字符存在于串。例如:

binary? '1011'
#=> true

binary? '0b1011'
#=> false

binary? '0xabc'
#=> false

答案 3 :(得分:0)

另一种方法:

str.chars.any?{|c| c!='0' && c!='1'}

答案 4 :(得分:0)

def binary?
  str.count("^01").zero?
end