我有一个在文本中包含名字和姓氏的字符串,如下所示:
"some text, 'Frances, David', some text, some text, 'Foljevic, Laura', some text, some text, Holjevic, Louis, some text, 'Staples, Cheri', some text"
Run Code Online (Sandbox Code Playgroud)
First, Last我想获取上面字符串中名称“ ”的列表。我正在尝试下面的表达
$Pattern = "'\w*, \w*'" ; $strText -match $Pattern; foreach ($match in $matches) {write-output $match;}
Run Code Online (Sandbox Code Playgroud)
但它只返回第一个匹配的 String 'Frances, David'。
我如何获得所有匹配的字符串?
von*_*ryz 10
操作员填充了不合适的-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'
Run Code Online (Sandbox Code Playgroud)
至于为什么-Match不完全按照人们预期的方式工作,文档解释道:
当运算符的输入(左侧参数)是单个标量对象时,-Match 和 -NotMatch 运算符将填充 $Matches 自动变量。当输入为标量时,-Match 和 -NotMatch 运算符返回布尔值,并将 $Matches 自动变量的值设置为参数的匹配组件。
当您传递单个字符串而不是集合时,这种行为有点令人惊讶。
编辑:
至于如何替换所有匹配项,请[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
Run Code Online (Sandbox Code Playgroud)