【问题标题】:How can I validate that a string holds only zeroes and ones?如何验证字符串只包含零和一?
【发布时间】:2014-03-02 15:17:37
【问题描述】:

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

我怎样才能做到这一点?

【问题讨论】:

    标签: ruby string validation


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        【解决方案3】:

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

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

        这将使用String#scan 扫描字符串中除零或一以外的任何字符,然后返回一个反转布尔值,如果Enumerable#any? 为真,则返回值为假,这意味着字符串中存在其他字符。例如:

        binary? '1011'
        #=> true
        
        binary? '0b1011'
        #=> false
        
        binary? '0xabc'
        #=> false
        

        【讨论】:

          【解决方案4】:

          另一种方法:

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

          【讨论】:

            【解决方案5】:
            def binary?
              str.count("^01").zero?
            end
            

            【讨论】:

              猜你喜欢
              • 2013-04-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-09-07
              • 1970-01-01
              相关资源
              最近更新 更多