Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Last active May 8, 2021 17:41
Show Gist options
  • Save ninmonkey/d6857bbd535ea6d90037d46be30d6f5f to your computer and use it in GitHub Desktop.
Save ninmonkey/d6857bbd535ea6d90037d46be30d6f5f to your computer and use it in GitHub Desktop.
Making Regex's readable using 'x' or .VERBOSE flags

Making regular expressions readable

What is easier to understand two months from now? Note that they are exactly equal in this example.

$regex = '(?n)(?<destination>(\d{1,3}\.){3}\d{1,3}).*time=(?<ms>\d+)ms'

verses

$regex = '(?xn)    
    # You can use in-line comments!

    # ip group:
    (?<destination>
        (
            \d{1,3}\.
        ){3}
        \d{1,3}
    )

    .*
    # Ping as Milliseconds
    time= 
    (?<ms>
        \d+    
    )
    ms
'

See more:

$cached = ping google.com
'Input: ', $cached
# the only change between these is the second adds the flag 'x'
# they are the exact same pattern
$regex_basic = '(?n)(?<destination>(\d{1,3}\.){3}\d{1,3}).*time=(?<ms>\d+)ms'
$regex_readable = '(?xn)
# You can use in-line comments!
# ip group:
(?<destination>
(
\d{1,3}\.
){3}
\d{1,3}
)
.*
# ping ms
time=
(?<ms>
\d+
)
ms'
"`n`$regex_basic:`n"
$results_basic = $cached | ForEach-Object {
Write-Debug "line: $_"
if ($_ -match $regex_basic ) {
# 'n' removed non-named capture groups
# then manually remove the full capture group: 0
$matches.Remove(0)
[pscustomobject]$matches
}
}
$results_basic | Format-Table
"`n`$regex_readable:`n"
$results_x = $cached | ForEach-Object {
Write-Debug "line: $_"
if ($_ -match $regex_readable ) {
$matches.Remove(0)
[pscustomobject]$matches
}
}
$results_x | Format-Table
# filter fast pings
$results_x | Where-Object Ms -GT 25 | ConvertTo-Json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment