首页 > 解决方案 > 如何使用正则表达式捕获多个未知数量的值

问题描述

我想使用正则表达式捕获多个字符串。我希望 $matches 将同时包含 a digitadigitbdigitc值。它似乎捕捉digita并停止。如果可能的话,我希望捕获与订单无关。我怎样才能做到这一点?

PS C:\src\t> $s2 = 'a=3 c=5 b=4'
PS C:\src\t> $s2 -match 'a=(?<digita>[0-9])|b=(?<digitb>[0-9])c=(?<digitc>[0-9])'
True
PS C:\src\t> $matches

Name                           Value
----                           -----
digita                         3
0                              a=3

标签: regexpowershell

解决方案


您可以扭转问题并执行以下操作:

,"a","b","c" | % { "$_=(?<digit$_>[0-9])" } | % { $s2 -match $_ } | % { $matches }

输出

Name                           Value                                                                                                                                                                   
----                           -----                                                                                                                                                                   
digita                         3                                                                                                                                                                       
0                              a=3                                                                                                                                                                     
digitb                         4                                                                                                                                                                       
0                              b=4                                                                                                                                                                     
digitc                         5                                                                                                                                                                       
0                              c=5 

推荐阅读