regex - 在 PowerShell 中使用正则表达式
问题描述
我有一个包含多个表达式的文件,例如$REGX('CareMedic.2_0','CustomerInformation','Customer Information')
. 该文件可以是 xml 文件、文本文件或任何其他类型。如果文件包含其中九个表达式,我将尝试提取所有九个。
我编写了如下代码:
$input_path = ‘C:\Users\rparpani\Desktop\test2.xml’
$output_file = 'C:\Users\rparpani\Desktop\test2.text'
$regex = '\$REGX'
$output = select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
Write-Output($output)
我的正则表达式似乎有问题。有人可以建议实现这一目标的正确方法吗?
解决方案
$
是正则表达式中的元字符,意思是“字符串结尾”,所以如果你正在寻找文字字符串$RESX
,你需要转义$
:
$regex = '\$REGX'
你也可以让它自动转义:
$regex = [regex]::Escape('$REGX')
推荐阅读
- javascript - 从导出的函数中反应类组件中的调用函数
- ansible - Ansible playbook 未在 GitHub Actions 中运行
- jquery - 仅使用 jQuery 从链接中删除元素
- sql - 从 SQL 填充用户表单上的复选框时,VBA 中的运行时错误 91
- python - 在 python 中跟踪散点图和视频
- cmake - 当我在字符串中有空格时,有没有办法避免 cmake 添加“\”?
- r - 推导R中所有可能矩阵的蛮力
- amazon-web-services - 在 AWS 服务中分离项目的最佳方式是什么?
- mysql - 为什么这些sql查询需要这么长时间才能执行
- c# - 网格视图中的行编辑 C#