Powershell返回找到的字符串



我使用Select-String找到一个子字符串,我不理解:它似乎返回整个父字符串或什么都没有,我错了吗?

如果不是,那不是我想要的:我想从它找到的位置得到字符串。是否有一个标准的函数,或者我应该创建自己的?

如果我们更仔细地检查数据,我们发现Select-String输出的MatchInfo对象包含行,以及匹配子字符串:

的信息。
PS C:> "string" |Select-String "." |Get-Member
TypeName: Microsoft.PowerShell.Commands.MatchInfo
Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
RelativePath Method     string RelativePath(string directory)
ToString     Method     string ToString(), string ToString(string directory)
Context      Property   Microsoft.PowerShell.Commands.MatchInfoContext Context {get;set;}
Filename     Property   string Filename {get;}
IgnoreCase   Property   bool IgnoreCase {get;set;}
Line         Property   string Line {get;set;}
LineNumber   Property   int LineNumber {get;set;}
Matches      Property   System.Text.RegularExpressions.Match[] Matches {get;set;}
Path         Property   string Path {get;set;}
Pattern      Property   string Pattern {get;set;}

Matches属性就是我们想要的:

$string  = "Hello there, user3101291!"
$pattern = "userd+"
$result = $string |Select-String -Pattern $pattern |Select -First 1
# this will give us only the actually matched part of the string
$result.Matches.Value

另一个选择是使用-match操作符和$Matches自动变量:

$string  = "Hello there, user3101291!"
$pattern = "userd+"
if($string -match $pattern){
# 0 = whole matched substring
$Matches[0]
}

$Matches最酷的地方,除了它的简单,是它也支持捕获组,我们可以得到更细粒度:

$string  = "Hello there, user3101291!"
$pattern = "user(?<numberPart>d+)"
if($string -match $pattern){
# 0 = whole matched substring
$Matches[0]
# 1 = first group
$Matches[1]
# But we can extract groups by name as well
$Matches['numberPart']
}

最新更新