Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 912
Stef Avatar asked Jun 27 '13 14:06

Stef


2 Answers

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'
like image 174
Dave Sexton Avatar answered Oct 13 '22 18:10

Dave Sexton


One way is:

$a = "[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS Server\anyLongString]"
$a -match '([^\\]*)]$'
$matches[1]
anyLongString
like image 21
CB. Avatar answered Oct 13 '22 18:10

CB.