regex - 打印Powershell Regex捕获到输出文件

标签 regex powershell

我有一个文件input.txt,其中包含如下文本:

GRP123456789
    123456789012
GRP234567890
    234567890123
GRP456789012
    "A lot of text. More text. Blah blah blah: Foobar." (Source Error) (Blah blah blah)
GRP567890123
    Source Error
GRP678901234
    Source Error
GRP789012345
    345678901234
    456789012345

我试图捕获所有出现的“GRP ##########”,条件是下一行至少有一个数字。

因此,GRP123456789有效,但GRP456789012和GRP678901234无效。

我在http://regexstorm.net/tester上想到的RegEx模式是:(GRP[0-9]{9})\s\n\s+[0-9]
到目前为止,基于该站点http://techtalk.gfi.com/windows-powershell-extracting-strings-using-regular-expressions/,我拥有的PowerShell脚本为:
$input_path = 'C:\Users\rtaite\Desktop\input.txt'
$output_file = 'C:\Users\rtaite\Desktop\output.txt'

$regex = '(GRP[0-9]{9})\s\n\s+[0-9]'

select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Values } > $output_file

我没有得到任何输出,也不确定为什么。

对此的任何帮助将不胜感激,因为我只是想更好地理解这一点。

最佳答案

您需要先将文本输入转换为单个字符串,然后再将其传递给Select-String,否则该cmdlet将单独在每一行上操作,因此永远找不到匹配项。

Get-Content $input_path | Out-String |
    Select-String $regex -AllMatches |
    Select-Object -Expand Matches |
    ForEach-Object { $_.Groups[1].Value } |
    Set-Content $output_file

如果您使用的是PowerShell v3或更高版本,则可以将Get-Content | Out-String替换为Get-Content -Raw

关于regex - 打印Powershell Regex捕获到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109331/

相关文章:

javascript - 正则表达式字符串开始/结束/中间一次匹配

regex - perl 搜索和追加

mysql - SQL "Not Like ' % %'"条件插入/更新

arrays - 如何使用 Invoke-Expression 在模板中使用运行命令?

powershell - Azure DevOps 托管代理管道 "Unable to locate executable file: ' Powershell'

c++ - 从 tr1::regex_search 获取匹配索引

php - preg_match_all 'OR' 运算符

javascript - 正则表达式匹配双引号或单引号中的字符串并后跟空格

尽管在 TFM 中尝试了所有内容,但 PowerShell Select-String 仍不匹配任何内容

windows - Windows Dockerfile 中的请求下载失败,错误为 'is not recognized'