regex - PowerShell 在匹配后检索 3 个字符
问题描述
我正在尝试使用 PowerShell 在字符串中匹配 3 个字符。例子:
$servername1 = "z002p002dcs001"
$serverName2 = "z002p003dcs001"
$servername3 = "z002p004dcs001"
我只对 , , , 之后的 3p
位002
数字003
感兴趣004
。我知道这里需要正则表达式,但我被卡住了。
$serverName1 -match "p002*"
True
好的
$serverName1 -match "p003*"
True
坏的
我究竟做错了什么?为什么"p003*"
返回匹配项$serverName1
?
解决方案
您的问题在于最后的星号 ( *
) 字符。只需将其删除即可解决您的问题。例如
$serverName1 -match "p002"
True
$serverName1 -match "p003"
False
您的第二个示例返回的原因True
是因为星号(*
)字符是“0 或更多”的正则表达式。所以你匹配的是:
p - Matches "p"
0 - Matches "0"
0 - Matches "0"
3 - Matches "3"
* - Quantifier, matches 0 or more of the preceding token. e.g. "3"
这意味着任何带有“p00”的东西都会匹配。
编辑:
除此之外,如果您对“p”之后的 3 位数字感兴趣,您可以使用捕获组和字符集:
"p([0-9]{3})"
p - Matches "p"
( - Start of Capture group
[0-9] - Character set. Match digits 0-9
{3} - Quantifier, matches 3 of the preceding token e.g. any digit 0-9
) - End Capture group
此外,在 PowerShell 中,您可以使用特殊$Matches
变量来提取数字:
$regex = "p([0-9]{3})"
$servername1 = "z002p002dcs001"
$serverName2 = "z002p003dcs001"
$servername3 = "z002p004dcs001"
$serverName1 -match $regex
$Matches[1]
002
$serverName2 -match $regex
$Matches[1]
003
$serverName3 -match $regex
$Matches[1]
004
推荐阅读
- c - 为什么使用非阻塞waitpid而不是阻塞等待?
- vue-router - Vue路由器从router-link访问元数据
- android - 在没有 Intent.createChooser 的情况下启动 Sharesheet
- python - 插入mongodb时如何设置字段类型
- swift2 - 具有协议 Logic Swift 2 的存在类型和泛型
- swiftui - SwiftUI 按钮不执行操作
- javascript - 尝试在第一次选择上选择一个选项后显示一个选择选项
- python - 错误 R14 和 H12,使用 heroku 部署工作人员超时
- php - 使用多个按钮从 FORM 外部获取输入值
- image - 预加载要在 Vue 中的图库中显示的图像