如何在 powershell 中使用正则表达式获取所有匹配字符串的列表?
How to get list of all matching strings using regex in powershell?
我有一个包含名字和姓氏的字符串,如下所示:
"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;}
但它 returns 只是首先匹配字符串 '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 and
[regex]::replace($strText, $pattern, "'` `'") # replace all matches with modified and
some text, 'David Frances', some text, some text, 'Laura Foljevic', some text, some text, Holjevic, Louis, some text, 'Cheri Staples', some text
我有一个包含名字和姓氏的字符串,如下所示:
"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;}
但它 returns 只是首先匹配字符串 '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 and
[regex]::replace($strText, $pattern, "'` `'") # replace all matches with modified and
some text, 'David Frances', some text, some text, 'Laura Foljevic', some text, some text, Holjevic, Louis, some text, 'Cheri Staples', some text