PoshCode Logo PowerShell Code Repository

Debug Regex match by Archdeacon 4 weeks ago
View followups from Archdeacon | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/3185"></script>download | new post

Debug Regex operation when matching any string

  1. <#
  2. .SYNOPSIS
  3. A very simple function to debug a Regex search operation and show any 'Match'
  4. results.
  5. .DESCRIPTION
  6. Sometimes it is easier to correct any regex usage if each match can be shown
  7. in context. This function will show each successful result in a separate
  8. colour, including the strings both before and after the match. Using the -F
  9. switch will allow only the first of any matches to be returned.
  10. .EXAMPLE
  11. Debug-Regex '\b[A-Z]\w+' 'Find capitalised Words in This string' -first
  12. Use the -F switch to return only the first match.
  13.  
  14. MATCHES  ---------------<match>--------------------
  15. 1 [<Find> capitalised Words in This string]
  16. .EXAMPLE
  17. Debug-Regex '\b[0-9]+\b' 'We have to find numbers like 123 and 456 in this'
  18.  
  19. MATCHES  ---------------<match>--------------------
  20. 1 [We have to find numbers like <123> and 456 in this]
  21. 2 [We have to find numbers like 123 and <456> in this]
  22. .NOTES
  23. Based on an idea from the book 'Mastering Regular Expressions' by J.Friedl,
  24. page 429.
  25. #>
  26.  
  27.  
  28. function Debug-Regex {
  29.    param ([Parameter(mandatory=$true)][regex]$regex,
  30.           [Parameter(mandatory=$true)][string]$string,
  31.           [switch]$first)
  32.    $m = $regex.match($string)
  33.    if (!$m.Success) {
  34.       Write-Host "No Match using Regex '$regex'" -Fore Yellow
  35.       return
  36.    }
  37.    $count = 1
  38.    Write-Host "MATCHES  ---------------<" -Fore Yellow -NoNewLine
  39.    Write-Host "match"                     -Fore White  -NoNewLine
  40.    Write-Host ">--------------------"     -Fore Yellow
  41.    while ($m.Success) {
  42.       Write-Host "$count $($m.result('[$`<'))" -Fore Yellow -NoNewLine
  43.       Write-Host "$($m.result('$&'))"          -Fore White  -NoNewLine
  44.       Write-Host "$($m.result('>$'']'))"       -Fore Yellow
  45.       if ($first) {
  46.          return
  47.       }
  48.       $count++
  49.       $m = $m.NextMatch()
  50.    }
  51. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me