Search code examples
regexpowershellsubstring

Extract a substring with a regular expression in PowerShell


Instead of splitting a string, how can I regex it and extract the last substring between \ and ]?

Example:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]

Solution

  • One way is:

    $a = "[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]"
    $a -match '([^\\]*)]$'
    $matches[1]
    anyLongString