首页 > 解决方案 > Powershell 正则表达式替换仅包含某些字符的行

问题描述

由于我执行的其他操作,我使用 get-content -raw读取了一个文件。

$c = get-content myfile.txt -raw

我想用“hare”替换仅包含字符“*”或“=”的每一行的全部内容

我试试

$c -replace "^[*=]*$","hare"

但这没有成功。它适用于简单的字符串输入,但不适用于包含 CRLF 的字符串。(其他不涉及字符类的正则表达式替换操作工作正常。)

测试:给定两行的输入文件

*=** 
keep this line ***
***=

输出应该是

hare
keep this line ***
hare

尝试了很多东西,没有运气。

标签: regexpowershell

解决方案


您应该使用(?m)( RegexOptions.Multiline) 选项来^匹配行首和$行尾位置。

但是,有一个警告:$带有多行选项的 .NET 正则表达式中的锚点仅在换行符 LF、"`n"、 char 之前匹配。您需要确保在$.

您可以使用

$file -replace "(?m)^[*=]*\r?$", "hare"

Powershell 测试演示:

PS> $file = "*=**`r`nkeep this line ***`r`n***=`r`n***==Keep this line as is"
PS> $file -replace "(?m)^[*=]*\r?$", "hare"
hare
keep this line ***
hare
***==Keep this line as is

推荐阅读