【问题标题】:PowerShell - Inserting newline char in string during regex replacePowerShell - 在替换期间在字符串中插入换行符
【发布时间】:2018-12-27 05:49:52
【问题描述】:

我正在尝试在字符串中搜索一些数字并在每个数字之前插入一个新行,不包括第一个。

我似乎无法使用传统的正则表达式 \n 字符来插入换行符。如果我使用 PowerShell 转义字符,则集合中的正则表达式变量将被忽略。

对于给定的源字符串

$theString = "1. First line 2. Second line 3. Third line"

我想要的是:

1. 第一行 2. 二线 3. 第三行

所以我尝试了这个正则表达式来找到数字 2 到 9 后跟一个句点和一个空格:

$theString = $theString -replace '([2-9]\. )','\n$1'

但这会产生:

1. 第一行\n2.第二行\n3.第三行

所以我尝试使用 PowerShell 转义字符作为换行符并将其放在双引号内:

$theString = $theString -replace '([2-9]\. )',"`n$1"

但这会产生:

1. 第一行 第二行 第三行

我尝试使用\r\r\n\`r\`r\`n 等来强制换行,但在不失去包含当前正则表达式变量的能力的情况下无法实现。

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    问题是因为$ 用于普通 Powershell 变量和捕获组。为了将其作为捕获组标识符进行处理,需要单引号 '。但是单引号告诉 Powershell 不要将换行符转义解释为换行符,而是文字 `n

    连接两个不同引用的字符串就可以了。像这样,

    $theString -replace '([2-9]\. )', $("`n"+'$1')
    1. First line
    2. Second line
    3. Third line
    

    作为替代方案,使用双引号 " 并转义美元。像这样,

    $theString -replace '([2-9]\. )', "`n`$1"
    1. First line
    2. Second line
    3. Third line
    

    另一个替代的(感谢 Lieven) 使用 here-strings。 here-string 包含换行符。也许一个变量使它更容易使用。像这样,

    $repl = @'
    
    $1
    '@
    
    $theString -replace '([2-9]\. )', $repl
    1. First line
    2. Second line
    3. Third line
    

    【讨论】:

    • 我更喜欢逃生解决方案。另一种解决方案是here 字符串,例如"1. First line 2. Second line 3. Third line" -replace '([2-9]\. )', @' $1 '@ (注意$1 之前有一个crlf!)
    • 谢谢,我现在明白了。第一种方法对我来说效果很好。奇怪的是 -Replace 命令会在单引号内找到一个换行符作为要搜索的内容。
    【解决方案2】:

    为了允许任何数字,我会用换行符替换前导空格并使用positive look ahead 进行过滤。

    $theString = "1. First line 2. Second line 3. Third line 11. Eleventh line"
    $thestring  -replace ' (?=[1-9]+\. )', "`n"
    

    样本输出:

    1. First line
    2. Second line
    3. Third line
    11. Eleventh line
    

    使用相同的正则表达式输出字符串数组:

    $thestring -split ' (?=[1-9]+\. )'
    

    【讨论】:

    • 有道理。我最终通过两次替换达到了同样的效果,如下所示: $theString = $theString -replace '([1-9][0-9]\. )', $("`n"+'$1') ...然后 $theString = $theString -replace '([2-9]\. )', $("`n"+'$1')
    【解决方案3】:

    另一种解决方案是:

    $theString = "1. First line 2. Second line 3. Third line"
    $theString -replace '(\s)([0-9]+\.)',([System.Environment]::NewLine+'$2')
    

    这实际上与您的第二行代码非常相似。

    【讨论】:

    • 是的,这也是一个不错的方法。
    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2017-11-14
    • 2013-05-23
    • 1970-01-01
    • 2013-12-08
    • 2017-03-06
    相关资源
    最近更新 更多