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]
Here's my solution:
$a = ('[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]' `
| Select-String -Pattern '([^\\]+)(?=])').Matches.Value
It uses Select-String to find the first match, then uses the .Matches.Value property to get the substring.
I prefer this because it's a single line and works even if a match is not found (unlike this solution), and it's explicit and elegant, unlike this solution which is more concise but seems abstruse.