Regex 从PowerShell中的字符串提取值(使用正则表达式)
我有以下文件:Regex 从PowerShell中的字符串提取值(使用正则表达式),regex,powershell,powershell-3.0,Regex,Powershell,Powershell 3.0,我有以下文件: <Mapping ServerPath="$/Test/Dev/test/sunday/project" LocalPath="$(SourceDir)\Test" Version="Latest" WorkspaceMappingType="Map"> <Mapping ServerPath="$/Test/Dev/test/aaa/project2" LocalPath="$(SourceDir)\Test\project" Version="Latest"
<Mapping ServerPath="$/Test/Dev/test/sunday/project" LocalPath="$(SourceDir)\Test" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/aaa/project2" LocalPath="$(SourceDir)\Test\project" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/sunday/project/test" LocalPath="$(SourceDir)\Test-machine" Version="Latest" WorkspaceMappingType="Map">
<Mapping ServerPath="$/Test/Dev/test/besaide/monday" LocalPath="$(SourceDir)\Monday" Version="Latest" WorkspaceMappingType="Map">
我使用此方法将文件内容设置为PS变量:
$file = Get-Content C:\test\file.txt
现在我如何用正则表达式从每行中检索2个值?(如果可能,也可以不使用正则表达式)。要提取这两条路径:
$input_path = 'C:\inputpath.txt'
$output_file = 'C:\outputpath.txt'
$regex = 'ServerPath=[^\s]+|LocalPath=[^\s]+'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
要提取这两条路径,请执行以下操作:
$input_path = 'C:\inputpath.txt'
$output_file = 'C:\outputpath.txt'
$regex = 'ServerPath=[^\s]+|LocalPath=[^\s]+'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file
除了缺少结束标记之外,您显示的输入看起来像一个XML变体。如果是这样,我建议使用XML工具而不是正则表达式:
Select-Xml -Path path\to\file.xml -XPath '//Mapping[@ServerPath and @LocalPath]'|%{
# grab the values of these
$_.Node.ServerPath
$_.Node.LocalPath
}
除了缺少结束标记之外,您显示的输入看起来像一个XML变体。如果是这样,我建议使用XML工具而不是正则表达式:
Select-Xml -Path path\to\file.xml -XPath '//Mapping[@ServerPath and @LocalPath]'|%{
# grab the values of these
$_.Node.ServerPath
$_.Node.LocalPath
}
非常感谢。它也有用!但是我更喜欢XML解决方案。谢谢!它也有用!但我更喜欢XML解决方案。