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

Validate RegEx pattern in PowerShell

Is it possible to validate pattern before creating RegEx object in PowerShell?

$Pattern = "[A-Z]{1,3" # Pattern is invalid
$Regex = [regex]::new($Pattern) # this throw an exception 

Let say that I have XML file with configuration and there are fields with pattern which will be used in the script. If pattern is not correct I’m getting an error which I would like to avoid.

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

>Solution :

If you want to avoid dealing with the exception (which you could do with try / catch, as Mathias shows in a comment), you can use the -as operator, which attempts conversion to a given RHS type, and quietly returns $null if that fails:

$valid = $null -ne ($regex = $pattern -as [regex])
  • $valid then contains a Boolean ($true or $false) that indicates whether $pattern contains a valid regex.

  • $regex then either contains a [regex] instance based on the pattern, or $null if the pattern isn’t valid.

    • If all you want to do is to validate the pattern itself, remove the $regex = part
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