如何从单行捕获多个正则表达式匹配到Powershell中的$ matches magic变量?

时间:2022-05-23 21:45:55

Let's say I have the string "blah blah F12 blah blah F32 blah blah blah" and I want to match the F12 and F32, how would I go about capturing both to the Powershell magic variable $matches?

假设我有字符串“blah blah F12 blah blah F32 blah blah blah blah”,我想要匹配F12和F32,我将如何捕获两个Powershell魔法变量$ matches?

If I run the following code in Powershell:

如果我在Powershell中运行以下代码:

$string = "blah blah F12 blah blah F32 blah blah blah"
$string -match "F\d\d"

The $matches variable only contains F12

$ matches变量仅包含F12

I also tried:

我也尝试过:

$string -match "(F\d\d)"

This time $matches had two items, but both are F12

这次$ match有两个项目,但都是F12

I would like $matches to contain both F12 and F32 for further processing. I just can't seem to find a way to do it.

我希望$ match包含F12和F32以进行进一步处理。我似乎无法找到办法。

All help would be greatly appreciated. :)

非常感谢所有的帮助。 :)

2 个解决方案

#1


33  

You can do this using Select-String in PowerShell 2.0 like so:

您可以使用PowerShell 2.0中的Select-String执行此操作,如下所示:

Select-String F\d\d -input $string -AllMatches | Foreach {$_.matches}

A while back I had asked for a -matchall operator on MS Connect and this suggestion was closed as fixed with this comment:

前段时间我曾在MS Connect上请求过一个-matchall运算符,这个建议已经关闭了,并附有以下注释:

"This is fixed with -allmatches parameter for select-string."

“这是通过select-string的-allmatches参数修复的。”

#2


14  

I suggest using this syntax as makes it easier to handle your array of matches:

我建议使用这种语法,以便更容易处理您的匹配数组:

$string = "blah blah F12 blah blah F32 blah blah blah" ;
$matches = ([regex]'F\d\d').Matches($string);
$matches[1].Value; # get matching value for second occurance, F32

#1


33  

You can do this using Select-String in PowerShell 2.0 like so:

您可以使用PowerShell 2.0中的Select-String执行此操作,如下所示:

Select-String F\d\d -input $string -AllMatches | Foreach {$_.matches}

A while back I had asked for a -matchall operator on MS Connect and this suggestion was closed as fixed with this comment:

前段时间我曾在MS Connect上请求过一个-matchall运算符,这个建议已经关闭了,并附有以下注释:

"This is fixed with -allmatches parameter for select-string."

“这是通过select-string的-allmatches参数修复的。”

#2


14  

I suggest using this syntax as makes it easier to handle your array of matches:

我建议使用这种语法,以便更容易处理您的匹配数组:

$string = "blah blah F12 blah blah F32 blah blah blah" ;
$matches = ([regex]'F\d\d').Matches($string);
$matches[1].Value; # get matching value for second occurance, F32