Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using regex in Powershell scripting to verify if a value is like another

I have a Powershell script using a -like to do a value comparison. I can write the regex using traditional regex methods and it works in the online testers I’ve used but I cannot get it to work in my script. I suspect it’s simply a syntax thing but all the sites I’ve referenced don’t address scripting specifically.

I’m checking namespaces to see if there are matches. For example,

www.domain.com
www.itdomain.com
www.anotherdomain.com
www.somedomain.com

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this example, I’d like to match only the first two options. This regex works at the tester mentioned above,
\.(it)?domain\.

Writing this in my script adds a small complication because the value "domain" is in a variable, so I’ve tried,

$domainUrl -like "*.(it)?$($domain).*" but the results are always false.

What am I missing in the Powershell syntax?

>Solution :

The -like operator matches against wildcard patterns, not regexes.

You want the -match operator.

Your pattern, "*.(it)?$($domain).*", is actually a mix of these two pattern languages, which won’t work.

Presumably, you meant something like the following:

$domain = 'domain'

'www.itdomain.com' -match "\.(it)?$domain\." # -> $true

Note that -match – unlike -like – matches substrings by default, so there’s no need to consume the input string as a whole with a given regex.

That is, the above matches a literal . (which must be escaped as \. in a regex) followed by either itdomain or domain ((it)? matches it if present (?)) and another literal . anywhere in the input string. For details, see this regex101.com page.
(The regex could be refined to make the matching more robust.)

For details on -like (wildcards) vs. -match (regexes), see this answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading