PowerShell正则表达式(五)搜索不同的关键字


你可以使用间隔结构“|”来搜索某一组关键字,然后找出那些实际上出现的关键字:

PS I:\> "Set a=1" -match "Get|GetValue|Set|SetValue"
True
PS I:\> $matches

Name                           Value
----                           -----
0                              Set

$matches会告诉你那些关键字实际上在字符串上出现了。但是要注意正则表达式中关键字的顺序。是因为第一个匹配到的关键字会被选中决定的。所以接下来的实例,结果感觉不正确:

PS I:\> "SetValue a=1" -match "Get|GetValue|Set|SetValue"
True
PS I:\> $matches[0]
Set

所以接下来更改关键字的顺序可以让较长的关键字被选中。

PS I:\> "SetValue a=1" -match "GetValue|Get|SetValue|Set"
True
PS I:\> $matches[0]
SetValue

或者,你可以更加精确地定制你的正则表达式,记住你实际上搜索的是一个独立的单词。所以在关键字中加入单词边界,让顺序的影响失效。

PS I:\> "SetValue a=1" -match "\b(Get|GetValue|Set|SetValue)\b"
True
PS I:\> $matches[0]
SetValue

也确实这样,-match只会搜索第一次匹配,如果你的源文本中可能须要和包含关键字的多次出现,可以重新使用RegEx

PS I:\> $regex = [regex]"\b(Get|GetValue|Set|SetValue)\b"
PS I:\> $regex.Matches("Set a=1; GetValue a; SetValue b=12")

Groups   : {Set, Set}
Success  : True
Captures : {Set}
Index    : 0
Length   : 3
Value    : Set

Groups   : {GetValue, GetValue}
Success  : True
Captures : {GetValue}
Index    : 9
Length   : 8
Value    : GetValue

Groups   : {SetValue, SetValue}
Success  : True
Captures : {SetValue}
Index    : 21
Length   : 8
Value    : SetValue

PS I:\> $regex.GetType().fullname
System.Text.RegularExpressions.Regex

上面的例子使用了.NET中的原始正则表达式类。

原始英文链接:http://powershell.com/cs/blogs/ebookv2/archive/2012/03/20/chapter-13-text-and-regular-expressions.aspx

本文链接: https://www.pstips.net/regex-searching-for-several-keywords.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注