Stef
Stef

Reputation: 623

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]

Upvotes: 14

Views: 48971

Answers (3)

Rachel
Rachel

Reputation: 1296

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.

Upvotes: 5

Dave Sexton
Dave Sexton

Reputation: 11188

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'

Upvotes: 13

CB.
CB.

Reputation: 60956

One way is:

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

Upvotes: 25

Related Questions