Home > database >  Compare multiple regex in if statement on powershell
Compare multiple regex in if statement on powershell

Time:11-10

How can i compare multiple regex on a if statement?

if ($file.Name -like "*test*", "*.tmp")  
{
    # do something
}

CodePudding user response:

Your two wildcard patterns can be combined as follows:

if ($file.Name -like "*test*.tmp")  
{
    # do something
}

CodePudding user response:

Unfortunately, neither -like, the wildcard matching operator, nor -match, the regular-expression matching operator, support an array of patterns to match against, as of PowerShell 7.2.x:

  • Having this ability (with any one of the patterns matching being considered an overall match) would be useful; GitHub issue #2132 asks for it to be implemented in a future PowerShell (Core) version.

  • While PowerShell currently reports no error when you try to use an array on the RHS, its current behavior is virtually useless: the array is stringified to form a single string, which means that its elements are joined with spaces; that is, $file.Name -like "*test*", "*.tmp" is the same as $file.Name -like "*test* *.tmp"

However, as a workaround you can use -match with a single regex pattern that uses alternation (|) to match one of multiple values:

if ($file.Name -match 'test|\.tmp$') {
  # do something
} 

Note:

  • -match matches substrings by default, so there's no need for regex equivalents to the * wildcard metacharacter.

    • Conversely, you need to anchor patterns if you want them to occur in a certain position, such as using $ above to assert that subexpression \.tmp matches at the end of the string.
  • regexes, which are much more powerful than wildcards, have many more metacharacters that may require escaping with \; in this case, metacharacter ., which matches any character, must be escaped as \. in order to be matched as a literal .


If you prefer to stick with -like, you need two operations, which you join with -or, as js2010 shows in a comment on the question:

if ($file.Name -like '*test*' -or $file.name -like '*.tmp') {
  # do something
}
  • Related