14

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]

3 Answers 3

25

One way is:

$a = "[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]"
$a -match '([^\\]*)]$'
$matches[1]
anyLongString
Sign up to request clarification or add additional context in comments.

Comments

13

Another way to do it is using fewer lines of code:

$a = "[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]"
$a -Replace '^.*\\([^\\]+)]$', '$1'

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.