首页 > 解决方案 > 在 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)

我的正则表达式似乎有问题。有人可以建议实现这一目标的正确方法吗?

标签: regexpowershell

解决方案


$是正则表达式中的元字符,意思是“字符串结尾”,所以如果你正在寻找文字字符串$RESX,你需要转义$

$regex = '\$REGX'

你也可以让它自动转义:

$regex = [regex]::Escape('$REGX')

推荐阅读