【问题标题】:Insert space at the beginning of line matched with lookarounds在与环视匹配的行首插入空格
【发布时间】:2021-10-15 09:31:35
【问题描述】:

我正在尝试在与环视匹配的行的开头添加空格。这是一个示例文本:

This is my 
first sentence
with 2 lines
that have to be indented. 

This is my 
second sentence
with 2 lines
that have to be indented. 

这是我想要得到的输出:

This is my 
    first sentence
    with 2 lines
that have to be indented. 

This is my 
    second sentence
    with 2 lines
that have to be indented. 

我试过用这个环顾四周: (?<=This is my)(.*?)(?=\nthat)

但是,我无法将行首与^ 匹配。也就是说,(?<=This is my)(^)(?=\nthat) 不起作用。

regex101

TIA!

【问题讨论】:

  • 您使用哪种编程语言?

标签: regex regex-lookarounds regexp-replace


【解决方案1】:
(.+?\n)(.+?\n)(.+?\n)(.+?\n)

https://regex101.com/r/Ryb3pR/1

似乎使用一些代码而不是使用正则表达式更容易理解。

【讨论】:

    【解决方案2】:

    如果后向断言(如 .NET、较新的 Javascript 引擎或 Python PyPi 正则表达式模块)支持量词,并且您想匹配任意数量的行,则可以使用:

    (?<=^This is my.*\n(?!that\b)(?:.*\n(?!that\b))*).*
    
    • (?&lt;= 肯定的后视断言左边是
      • ^ 字符串开始
      • This is my.*\n(?!that\b) 匹配第一行,下一行断言不是that
      • (?:非捕获组
        • .*\n(?!that\b) 匹配包括换行在内的整行,并在下一个断言不是that
      • )*关闭非捕获组
    • ) 近距离观察
    • .*整行匹配

    Regex demo

    const regex = /(?<=^This is my.*\n(?!that\b)(?:.*\n(?!that\b))*).*/gm;
    const str = `This is my 
    first sentence
    with 2 lines
    that have to be indented. 
    
    This is my 
    second sentence
    testing
    with 3 lines
    that have to be indented. 
    test
    
    This is my 
    that have to be indented. `;
    console.log(str.replace(regex, `    $&`));

    没有列出语言,但另一种选择是使用 2 个捕获组,并将缩进添加到第二组中的所有行。

    该模式捕获第 1 组中的起始行,然后捕获第 2 组中不以 that 开头的所有行

    ^(This is my.*)((?:\n(?!that\b).*)*)(?=\nthat\b)
    

    Regex demo

    例如使用 Javascript:

    const regex = /^(This is my.*)((?:\n(?!that\b).*)*)(?=\nthat\b)/gm;
    const str = `This is my 
    first sentence
    with 2 lines
    that have to be indented. 
    
    This is my 
    second sentence
    testing
    with 3 lines
    that have to be indented. 
    test
    
    This is my 
    that have to be indented. `;
    console.log(str
      .replace(regex, (m, g1, g2) => g1 + g2
        .split('\n').map(s => '    ' + s)
        .join('\n'))
    );

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多