代码之家  ›  专栏  ›  技术社区  ›  lonix

Regex匹配线仅当前面没有空行时

  •  1
  • lonix  · 技术社区  · 3 年前

    我需要匹配一个前面没有空行的行,并在它前面加一个换行符。

    所以我想转变一下:

    a = 1
    b = 2
    
    # header                    <--- do not match this
    f = 10
    g = 20
    # header                    <--- match this
    x = abc
    y = def
    

    对此:

    a = 1
    b = 2
    
    # header
    f = 10
    g = 20
    
    # header
    x = abc
    y = def
    

    我试过了 (?!\n)(# header) 有替换 \n\1 ,但这两行都匹配: regex101 sample 。

    (我需要这个作为ansible,所以它是python正则表达式。)

    为了满足下面的评论,请注意“空”行实际上是空的;它不包含空白。

    2 回复  |  直到 3 年前
        1
  •  2
  •   Cary Swoveland    3 年前

    您可以替换的(零宽度)匹配项

    (?<=(?<!\n)\n)(?=# header$)
    

    具有 "\n" 。

    Demo

    正则表达式可以分解如下。

    (?<=         # begin positive lookbehind
      (?<!       # begin negative lookbehind
        \n       # match literal
      )          # end negative lookbehind
      \n         # match literal
    )            # end positive lookbehind
    (?=          # begin positive lookahead
      # header   # match literal
      $          # match end of string
    )            # end positive lookahead
    

    注意,积极的背后看

    (?<=(?<!\n)\n)
    

    具有与(相同的效果,可以替换为)

    (?<=\n)(?<!\n\n)
    
        2
  •  0
  •   David542    3 年前

    我不确定您要针对哪种语言,但这里有一个Javascript中的例子,使用 String.replace :

    let original = 
    `a = 1
    b = 2
    
    # header
    f = 10
    g = 20
    # header
    x = abc
    y = def`;
    
    let replaced = original.replace(/(?<!\n\n)(# header)/, '\n$1');
    console.log(replaced);

    或者在python中来自 Codepen :

    import re
    s='''a = 1
    b = 2
    
    # header
    f = 10
    g = 20
    # header
    x = abc
    y = def'''
    x = re.sub(r'(?<!\n\n)(# header)', r'\n\1', s)
    print(x)