Regex 如何在powershell中使用正则表达式获取所有匹配字符串的列表?
我有一个包含名字和姓氏的字符串,如下所示:Regex 如何在powershell中使用正则表达式获取所有匹配字符串的列表?,regex,powershell,Regex,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 -
"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。使用regex Accelerator和类似的MatchCollection
至于为什么-Match不能像人们想象的那样工作,他解释道:
-Match和-NotMatch操作符自动填充$Matches
当运算符左侧参数的输入为
单个标量对象。当输入为标量时,-Match和
-NotMatch运算符返回一个布尔值,并将$Matches自动变量的值设置为参数的匹配组件
当您传递的是单个字符串而不是集合时,这种行为有点令人惊讶
编辑:
至于如何替换所有匹配项,请使用[regex]::替换为捕获组
$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
嗨,vonPryz,有没有一种直接的方法可以使用正则表达式将上述字符串$strText中的“First,Last”替换为“First-Last”?目前,我正在对for循环中的输出匹配集合进行迭代。@user3835927是,使用[regex]::替换为捕获组。有关示例,请参见编辑的文章。对于复杂的修改,循环匹配集合的编写和理解要比针对一行程序简单得多。
$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