regex - 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=”)
解决方案
您可以在此处使用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}
推荐阅读
- wordpress - wordpress 页面中的资产链接是如何建立的?移到 docker 后我得到的是 http 而不是 https
- android - 清除 Android 导航组件中的返回堆栈
- google-cloud-platform - GCP Python SDK - 在没有 gcloud 的情况下启用 API
- php - 获取数据后如何选择下拉列表
- reactjs - 顺风CSS渐变问题
- linux - Bash:使用 bash 脚本抓取文本文件以查找电话号码
- javascript - 如何自动调用类中的函数
- ios - Getting an image-related exception when using a ListWheelScrollView in Flutter
- android - Android Kotlin - 在工具栏内设置徽标
- postgresql - 针对真实 postgres 数据库的 Spring Boot 集成测试