通过 Powershell 从文本文件中提取字符串

Arb*_*lac 5 regex powershell

我一直在尝试使用 PowerShell 从 .txt 文件内的多行中提取某些值。

Host
Class
INCLUDE vmware:/?filter=Displayname Equal "server01" OR Displayname Equal "server02" OR Displayname Equal "server03 test"
Run Code Online (Sandbox Code Playgroud)

这就是我要的 :

server01
server02
server03 test
Run Code Online (Sandbox Code Playgroud)

到目前为止我有代码:

$Regex = [Regex]::new("(?<=Equal)(.*)(?=OR")           
$Match = $Regex.Match($String)
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 4

您可以使用

[regex]::matches($String, '(?<=Equal\s*")[^"]+')
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

请参阅此处提取多个匹配项的更多方法。但是,您的主要问题是正则表达式模式。模式(?<=Equal\s*")[^"]+匹配:

  • (?<=Equal\s*")- 一个位置前面有Equal0+ 个空格,然后是"
  • [^"]+- 除双引号外,消耗 1+ 个字符。

演示:

$String = "Host`nClass`nINCLUDE vmware:/?filter=Displayname Equal ""server01"" OR Displayname Equal ""server02"" OR Displayname Equal ""server03 test"""
[regex]::matches($String, '(?<=Equal\s*")[^"]+') | Foreach {$_.Value}
Run Code Online (Sandbox Code Playgroud)

输出:

server01
server02
server03 test
Run Code Online (Sandbox Code Playgroud)

这是读取文件、获取所有匹配项并保存到文件的完整片段:

$newfile = 'file.txt'
$file = 'newtext.txt'
$regex = '(?<=Equal\s*")[^"]+'
Get-Content $file | 
     Select-String $regex -AllMatches | 
     Select-Object -Expand Matches | 
     ForEach-Object { $_.Value } |
     Set-Content $newfile
Run Code Online (Sandbox Code Playgroud)