【问题标题】:Ruby regex that starts with ONLY one opening bracket仅以一个左括号开头的 Ruby 正则表达式
【发布时间】:2018-08-22 15:29:26
【问题描述】:

我正在寻找一个正则表达式,它检查仅以 1 个左大括号和任意数量的右括号开头的模式:

"something{word_or_not}}}}}}}"  
#should return true.  

"something{{word_or_not}}}}}}}}"  
#should return false.  

这是我得到"\{\w*\}\}+" 的距离,除了没有那么远,因为第二个示例返回true

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    这个正则表达式可能适合:

    str1 = "{word_or_not}}}}}}}"
    str2 = "{{word_or_not}}}}}}}}"
    
    str1.match?(/\A\{[^{]*?\}+\z/) #=> true
    str2.match?(/\A\{[^{]*?\}+\z/) #=> false
    

    【讨论】:

      【解决方案2】:

      Try这个正则表达式:

      (?<!{){\w*}+
      

      这使用否定的lookbehind 断言在第一个{ 之前没有{

      【讨论】:

        【解决方案3】:

        可能会明确检查negative lookbehind

        %w|{word_or_not}}}}}}} {{word_or_not}}}}}}}|.
          map(&/(?<!{){\w+}+/.method(:=~))
        #⇒ [0, nil]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-31
          • 1970-01-01
          相关资源
          最近更新 更多