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

Regex是否只在文本不在空行之前的行上匹配换行符?

  •  3
  • Chris  · 技术社区  · 2 年前

    我试图用markdown换行符替换诗歌markdown文件中的换行符,这意味着在a)有文本和b)不在空行之前的行的末尾添加两个空格。

    因此,以下文本:

    this line should have a break
    and this one
    but not this one
    
    and this one should
    and this one
    but not this one
    
    and so on
    

    将在X出现的位置添加两个空格:

    this line should have a breakX
    and this oneX
    but not this one
    
    and this one shouldX
    and this oneX
    but not this one
    
    and so on
    

    我的困惑似乎找不到正确的咒语。我想到的最接近的是 (.*?)\n(?!\n) 但它也匹配空行。

    1 回复  |  直到 2 年前
        1
  •  2
  •   bobble bubble    2 年前

    您可以查看 非空白 \S 之前 \n capture group :

    (.*\S)\n(?!\n)
    

    在替换中插入捕获和空格: $1 \n (regex101 demo)


    或者如果 lookbehind 支持,只需替换 (?<!\s)\n(?!\n) 具有 \n