regex - Powershell 正则表达式替换仅包含某些字符的行
问题描述
由于我执行的其他操作,我使用 get-content -raw读取了一个文件。
$c = get-content myfile.txt -raw
我想用“hare”替换仅包含字符“*”或“=”的每一行的全部内容
我试试
$c -replace "^[*=]*$","hare"
但这没有成功。它适用于简单的字符串输入,但不适用于包含 CRLF 的字符串。(其他不涉及字符类的正则表达式替换操作工作正常。)
测试:给定两行的输入文件
*=**
keep this line ***
***=
输出应该是
hare
keep this line ***
hare
尝试了很多东西,没有运气。
解决方案
您应该使用(?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
推荐阅读
- python - 无法在我的 django 项目中使用多个数据库
- sql - 获取消息 241、级别 16、状态 1、第 33 行的转换问题
- google-sheets - 在 Google 表格中创建混淆矩阵的自动化方法?
- sql-server - EF迁移中使用多条SQL语句——如何使用GO在SSMS中运行?
- c# - 使用 LINQ 创建元组列表
- spring - Spring Batch端到端测试配置不起作用
- iis - 404 未使用查询子路径找到文件或目录
- tensorflow - 具有梯度计算的自定义损失函数
- android - 通过单击菜单按钮打开 Activity - Android Studio
- node.js - 无法在 express.js 4.x 中获取特定路由中的表单数据