如何解决是否可以将 Powershell 正则表达式中捕获的组分配给没有 IF 块的变量?
$text = "blah blah blah,yada yada yada,foobar"
If ($text -match '^.*(?<found>foobar).*$') {
$foundtext = $Matches.found
}
$foundtext
但我想知道如何做到这一点:
$text = "blah blah blah,foobar"
$foundtext = ($text -match '^.*(?<found>foobar).*$').found
$foundtext
也就是说,我想知道是否可以将正则表达式中捕获的组直接分配给变量,而不必将其包装在 IF 语句中。问题在于 $text -match '^.*(?<found>foobar).*$'
正则表达式匹配代码的计算结果为 $True
或 $False
。
更通俗地说,我希望代码说“将变量 $foundtext
设置为等于表达式 found
中名为 ($text -match '^.*(?<found>foobar).*$')
的捕获组"
这可能吗? 是吗,正确的语法是什么?
解决方法
正如 Mathias 已经评论过的,您可以使用 $Matches
来获取值。
如果你想在一行代码中得到匹配的值,你也可以这样做:
$text = "blah blah blah,yada yada yada,foobar"
# using the capture groups index:
$foundtext = ([regex]'(?i)^.*(?<found>foobar).*$').Match($text).Groups[1].Value
# or by the capture group's Name:
$foundtext = ([regex]'(?i)^.*(?<found>foobar).*$').Match($text).Groups['found'].Value
(?i)
使正则表达式不区分大小写,如 -match
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。