我有一个脚本,我正在处理它来解析日志中的每一行。我的问题是我使用的正则表达式匹配从src=直到空格。
我只想要ip地址,而不是src=部分。但我仍然需要从src=到空格进行匹配,但结果中只存储数字。下面是我使用的,但它真的很糟糕。所以任何帮助都会对有帮助
#example text
$destination=“src=192.168.96.112 dst=192.168.5.22”
$destination -match 'src=[^s]+'
$result = $matches.Values
#turn it into string since trim doesn’t work
$result=echo $result
$result=$result.trim(“src=”)
您可以在此处使用lookbacking,由于-match
只返回第一个匹配,因此您可以使用$matches[0]
:访问匹配的值
$destination -match '(?<=src=)S+' | Out-Null
$matches[0]
# => 192.168.96.112
请参阅.NET regex演示。
(?<=src=)
-匹配紧跟在src=
前面的位置S+
-一个或多个非空白字符
要提取所有这些值,请使用
Select-String '(?<=src=)S+' -input $destination -AllMatches | Foreach {$_.Matches} | Foreach-Object {$_.Value}
或
Select-String '(?<=src=)S+' -input $destination -AllMatches | % {$_.Matches} | % {$_.Value}
另一种方法可以是使用捕获组:
src=(S+)
Regex演示| Powershell演示
例如
$destination=“src=192.168.96.112 dst=192.168.5.22”
$pattern = 'src=(S+)'
Select-String $pattern -input $destination -AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[1].Value}
输出
192.168.96.112
或更具体的匹配点和数字(或参见本页了解ip号码的更具体匹配(
src=(d{1,3}(?:.d{1,3}){3})