gpt4 book ai didi

regex - 如何在powershell中使用正则表达式获取所有匹配字符串的列表?

转载 作者:行者123 更新时间:2023-12-03 01:16:42 25 4
gpt4 key购买 nike

我有一个包含名字和姓氏的字符串,如下所示:

"some text, 'Frances, David', some text, some text, 'Foljevic, Laura', some text, some text, Holjevic, Louis, some text, 'Staples, Cheri', some text"

我想得到一个名字列表 ' First, Last ' 在上面的字符串中。我正在尝试以下表达式
$Pattern = "'\w*, \w*'" ; $strText -match $Pattern; foreach ($match in $matches) {write-output $match;}

但它只返回第一个匹配的字符串 'Frances, David' .

我将如何获得所有匹配的字符串?

最佳答案

-Match运算符填充自动变量 $Matches那不合适。使用正则表达式加速器和 MatchCollection像这样,

$mc = [regex]::matches($strText, $pattern)
$mc.groups.count
3
$mc.groups[0].value
'Frances, David'
$mc.groups[1].value
'Foljevic, Laura'
$mc.groups[2].value
'Staples, Cheri'

为什么 -Match不像人们期望的那样工作, the documentation解释:

The -Match and -NotMatch operators populate the $Matches automatic variable when the input (the left-side argument) to the operator is a single scalar object. When the input is scalar, the -Match and -NotMatch operators return a Boolean value and set the value of the $Matches automatic variable to the matched components of the argument.



当您传递单个字符串而不是集合时,这种行为有点令人惊讶。

编辑:

至于如何替换所有匹配,使用 [regex]::replace()与捕获组。
$pattern = "'(\w*), (\w*)'" # save matched string's substrings to $1 and $2
[regex]::replace($strText, $pattern, "'`$2 `$1'") # replace all matches with modified $2 and $1

some text, 'David Frances', some text, some text, 'Laura Foljevic', some text, some text, Holjevic, Louis, some text, 'Cheri Staples', some text

关于regex - 如何在powershell中使用正则表达式获取所有匹配字符串的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com