Russell Maycock
Russell Maycock

Reputation: 29

regex expression to match and not match

I'm using powershell and want to use regex to match something. I've got a list of servers that have this naming convention - ABCPPsomename.
So when regex finds PP in a name I want it included.

However some of the servers have the name ABCPRODsomenAppame and the match is including these servers becasue of the App in the name.

I need it so if the PP is in the name to include it and if it's not in the name to leave it out. Also I need servers name that are ABCPPsomeAppname to be included

Upvotes: 0

Views: 234

Answers (2)

mklement0
mklement0

Reputation: 438153

Note: This answers shows how to match case-sensitively, which turned out not to be what the OP wanted.


It sounds like you want to match server names that contain substring PP case-sensitively, so that PP matches, but App doesn't, for instance.

For case-sensitive matching, use the -cmatch operator:

PS> 'PPOnly', 'OnlyApp', 'PPandApp', 'Neither' -cmatch 'PP'
PPOnly
PPandApp

More work is needed if the substring should only be matched at a certain position.

Note:

  • The above command operates directly on an input array and returns the filtered array.

  • If you want to filter via the pipeline, see Theo's Where-Object-based answer.

Upvotes: 1

Theo
Theo

Reputation: 61093

IF (big if because you are not clear on this) all your servers start their name with the literal text ABC, then yes, it would not be hard to do:

$servers = @('ABCPPsomename', 'ABCPRODsomenAppame', 'ABCPPsomeAppname')
$servers | Where-Object { $_ -match '^ABCPP' }

Result

ABCPPsomename
ABCPPsomeAppname


UPDATE
From your latest comment, I gather that the servername convention should be 3 to a maximum of 5 characters to start with, followed by either PP or something totally different like PROD.

To find only the "PP" servers in the list, you might try this instead:

$servers = 'ABCPPsomename', 'ABCPRODsomenAppame', 'ABCPPsomeAppname'
$servers | Where-Object { $_ -match '^[A-Z]{3,5}PP' }

Result:

ABCPPsomename
ABCPPsomeAppname

Regex details:

^          Assert position at the beginning of the string
[A-Z]      Match a single character in the range between “A” and “Z”
   {3,5}   Between 3 and 5 times, as many times as possible, giving back as needed (greedy)
PP         Match the characters “PP” literally

If you need the match to be case sensitive, use -cmatch instead.

Hope that helps

Upvotes: 1

Related Questions