Regex PowerShell-在替换期间在字符串中插入换行符

Regex PowerShell-在替换期间在字符串中插入换行符,regex,powershell,Regex,Powershell,我试图在字符串中搜索一些数字,并在每个数字前插入新行,不包括第一行 我似乎无法使用传统的regex字符插入换行符。如果使用PowerShell转义字符,则会忽略集合中的regex变量 对于给定的源字符串 $theString = "1. First line 2. Second line 3. Third line" 我想要的是: 1. First Line 2. Second Line 3. Third line 但这会产生: 1. First line\n2. Second line\n3

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

我似乎无法使用传统的regex字符插入换行符。如果使用PowerShell转义字符,则会忽略集合中的regex变量

对于给定的源字符串

$theString = "1. First line 2. Second line 3. Third line"
我想要的是:

1. First Line 2. Second Line 3. Third line 但这会产生:

1. First line\n2. Second line\n3. Third line 1. First Line Second Line Third line 但这会产生:

1. First line\n2. Second line\n3. Third line 1. First Line Second Line Third line 1.一线 第二线 第三行
我尝试使用
\r
\r\n
\`r
\`r\`n
等来强制换行,但无法在不丢失包含当前regex变量的能力的情况下实现换行。

问题是由于
$
同时用于普通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
$repl = @'

$1
'@

$theString -replace '([2-9]\. )', $repl
1. First line
2. Second line
3. Third line
另一种方法是,使用双引号
并避开美元。就像这样

$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
$repl = @'

$1
'@

$theString -replace '([2-9]\. )', $repl
1. First line
2. Second line
3. Third line
还有一种替代方法(感谢Lieven)使用here字符串。here字符串包含一个换行符。也许变量更易于使用。就像这样

$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
$repl = @'

$1
'@

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

若要允许任何数字,我将用换行符替换前导空格,并使用a进行筛选

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

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

我更喜欢转义解决方案。另一种解决方案是这里的
字符串,如
“1。第一行2。第二行3。第三行“-替换“([2-9]\”,@“$1”@
(注意$1之前有一个crlf!)谢谢,我现在明白了。第一种方法对我来说效果很好。奇怪的是-Replace命令会在单引号内找到一个换行字符作为搜索对象。是的,这也是一种很好的方法。这是有道理的。我最后通过两次Replace实现了同样的效果,如下所示:$theString=$theString-Replace'([1-9][0-9]\),$(”`n“+”$1“…然后是$theString=$theString-replace“([2-9]\)”,$(“`n”+“$1”)