首页 > 解决方案 > Powershell 正则表达式仅选择数字

问题描述

我有一个正在处理的脚本来解析日志中的每一行。我的问题是我使用从 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=”)

标签: regexpowershell

解决方案


您可以在此处使用lookbehind,并且由于-match只返回第一个匹配项,您将能够使用以下方式访问匹配的值$matches[0]

$destination -match '(?<=src=)\S+' | Out-Null
$matches[0]
# => 192.168.96.112

请参阅.NET 正则表达式演示

  • (?<=src=)- 匹配紧接在前面的位置src=
  • \S+ - 一个或多个非空白字符。

要提取所有这些值,请使用

Select-String '(?<=src=)\S+' -input $destination -AllMatches | Foreach {$_.Matches} | Foreach-Object {$_.Value}

或者

Select-String '(?<=src=)\S+' -input $destination -AllMatches | % {$_.Matches} | % {$_.Value}

推荐阅读