In the below example, I am expecting to get an output of ;[rr] [Delete]
. But I am instead getting Sendinput, {F3}
:
$Name = "Sendinput, {F3} ;[rr] [Delete]"
$name -replace "(;\[rr\].*)", "$1"
Sendinput, {F3}
Isnt this (;\[rr\].*)
a capture group??
I am so cofused, What could I be doing wrong?
CodePudding user response:
The problem are the double-quotes instead of single-quotes, PowerShell is interpreting $1
as a variable instead of a capture group (variables are expanded in a double-quoted string) and since the variable is not defined it's actually replacing the regex match with null.
But also, you're looking to replace everything with the capturing group 1, so your regex should be something like this:
$name = 'Sendinput, {F3} ;[rr] [Delete]'
$name -replace '. (;\[rr\].*)', '$1'
See https://regex101.com/r/ikQzhc/1 for details.
Worth noting you could do this with -match
or Regex.Match
instead:
if($name -match ';\[rr\].*') { $Matches[0] }
# or
[regex]::Match($name, ';\[rr\].*').Value