如何在 Powershell 中提取正则表达式反向引用/匹配的值 [英] How do you extract the value of a regex backreference/match in Powershell

查看:28
本文介绍了如何在 Powershell 中提取正则表达式反向引用/匹配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数据行的文本文件.我可以使用以下 powershell 脚本来提取我感兴趣的行:

I have a text file containing lines of data. I can use the following powershell script to extract the lines I'm interested in:

select-string -path *.txt -pattern "subject=([A-Z\.]+),"

一些示例数据是:

blah blah subject=THIS.IS.TEST.DATA, blah blah blah

我想要的是能够提取主题的实际内容(即THIS.IS.TEST.DATA"字符串).我试过这个:

What I want is to be able to extract just the actual contents of the subject (i.e. the "THIS.IS.TEST.DATA" string). I tried this:

select-string -path *.txt -pattern "subject=([A-Z\.]+)," | %{ $_.Matches[0] }

但匹配"属性始终为空.我做错了什么?

But the "Matches" property is always null. What am I doing wrong?

推荐答案

我不知道为什么你的版本不起作用.它应该工作.这是一个有效的丑陋版本.

I don't know why your version doesn't work. It should work. Here is an uglier version that works.

$p = "subject=([A-Z\.]+),"
select-string -path *.txt -pattern $p | % {$_ -match $p > $null; $matches[1]}

说明:

-match 是正则表达式匹配运算符:

-match is a regular expression matching operator:

>"foobar" -match "oo.ar"
True

<代码>>$null 只是抑制写入输出的 True.(尝试删除它.)有一个 cmdlet 执行相同的操作,我现在不记得它的名字了.

The > $null just suppresses the True being written to the output. (Try removing it.) There is a cmdlet that does the same thing whose name I don't recall at the moment.

$matches 是一个魔法变量,它保存最后一个 -match 操作的结果.

$matches is a magic variable that holds the result of the last -match operation.

这篇关于如何在 Powershell 中提取正则表达式反向引用/匹配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆