Your issue is with the asterix (*
) character at the end. Simply removing it will fix your problem. e.g.
$serverName1 -match "p002"
True
$serverName1 -match "p003"
False
The reason why your second example returned True
is because the asterix (*
) character is regex for "0 or more". So what you are matching is:
p - Matches "p"
0 - Matches "0"
0 - Matches "0"
3 - Matches "3"
* - Quantifier, matches 0 or more of the preceding token. e.g. "3"
This means that anything with "p00" will match.
Edit:
Going beyond, if you are interested in the 3 digits after the "p" you can use a capture group and a character set:
"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
Also, in PowerShell, you can then use the special $Matches
variable to extract the number:
$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