代码之家  ›  专栏  ›  技术社区  ›  Vikrant Chaudhary

不匹配两个下划线的正则表达式

  •  2
  • Vikrant Chaudhary  · 技术社区  · 16 年前

    在Ruby的正则表达式中,如何匹配不包含两个连续下划线的字符串,即“\uuuu”。

    Matches: "abcd", "ab_cd", "a_b_cd", "%*##_@+"
    Does not match: "ab__cd", "a_b__cd"
    

    -谢谢

    比赛 .

    4 回复  |  直到 16 年前
        1
  •  4
  •   Mark Byers    16 年前
    /^([^_]*(_[^_])?)*_?$/
    

    测验:

    regex=/^([^_]*(_[^_])?)*_?$/
    
    # Matches    
    puts "abcd" =~ regex
    puts "ab_cd" =~ regex
    puts "a_b_cd" =~ regex
    puts "%*##_@+" =~ regex
    puts "_" =~ regex
    puts "_a_" =~ regex
    
    # Non-matches
    puts "__" =~ regex
    puts "ab__cd" =~ regex
    puts "a_b__cd" =~ regex
    

    但对于这项任务来说,正则表达式是矫枉过正的。简单的字符串测试要容易得多:

    puts ('a_b'['__'])
    
        2
  •  10
  •   Andomar    16 年前

    ^((?!__).)*$
    

    弦的开头 ^ 最后 $

        3
  •  2
  •   user222229 user222229    16 年前

    改变你的逻辑仍然有效吗?

    您可以使用正则表达式[]{2}检查字符串是否包含两个下划线,然后忽略它?

        4
  •  0
  •   Amarghosh    16 年前

    消极前瞻

    \b(?!\w*__\w*)\w+\b
    

    编辑:要在匹配中容纳除空白以外的任何内容:

    (?!\S*__\S*)\S+
    

    如果您希望容纳符号的子集,您可以编写如下内容,但它将匹配 _cd a_b__cd 除其他外。

    (?![a-zA-Z0-9_%*#@+]*__[a-zA-Z0-9_%*#@+]*)[a-zA-Z0-9_%*#@+]+
    
    推荐文章