微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以将 Powershell 正则表达式中捕获的组分配给没有 IF 块的变量?

如何解决是否可以将 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?