Skip to content

Instantly share code, notes, and snippets.

@pkutaj
Created August 19, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkutaj/e8ecc82e55da95508ea0a57711f1b7a0 to your computer and use it in GitHub Desktop.
Save pkutaj/e8ecc82e55da95508ea0a57711f1b7a0 to your computer and use it in GitHub Desktop.
powershell regex matches.md

THE CASE OF WORK WITH REGEX MATCHES

the case

the puzzle is, how to assign a match in regex search to a new variable: to test-path it and eventually create a folder, if the test fails.

solution

Use the -match with your regex and find the matches in the build-in $matches hash table!

sources

terminology

  • $matches

changelog

2019-08-09 12:09:53 built-in feature!  

  • PowerShell stores matches from the -match operator in the $matches[] hash table.
  • Example:
 # 2.3.4 | TEST the path and create the new folder if the year changes
    If ($filePrefix.Node.InnerText -match $regexFilePath) {
        $filePath = $matches[0]
        If (-Not (test-path $filePath)) {
            New-Item -ItemType Directory -Path $filePath 
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment