首页 > 解决方案 > PowerShell 在匹配后检索 3 个字符

问题描述

我正在尝试使用 PowerShell 在字符串中匹配 3 个字符。例子:

$servername1 = "z002p002dcs001"
$serverName2 = "z002p003dcs001"
$servername3 = "z002p004dcs001"

我只对 , , , 之后的 3p002数字003感兴趣004。我知道这里需要正则表达式,但我被卡住了。

$serverName1 -match "p002*"
True

好的

$serverName1 -match "p003*"
True

坏的

我究竟做错了什么?为什么"p003*"返回匹配项$serverName1

标签: regexpowershell

解决方案


您的问题在于最后的星号 ( *) 字符。只需将其删除即可解决您的问题。例如

$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

推荐阅读