Home > Software engineering >  powershell How to capture 'left side' of the -replace regex?
powershell How to capture 'left side' of the -replace regex?

Time:12-03

First time posting.

i have the following code to replace the suffix of an email and its working fine

replace all characters after @ sign with @testdomain.com

$a = '[email protected]'
$b = $a -replace "[?=@].*", '@testdomain.com'
$b
[email protected]

what i would like to do, is to capture the actual left side 'source' regex expression to a variable, which would be @domain.com so that i know what i;m replacing and i don;t know how to do it.

Sorry if this had been posted before.

Thank you

CodePudding user response:

So, I'm not sure if this is possible using only the -replace operator and without the use of -match which would store the capture group on the $Matches automatic variable.

This is how you could do it using the regex class directly:

$a = '[email protected]'
$Capture = @{}

$b = [regex]::Replace($a, "[?=@].*", {
    param($s)
    
    '@testdomain.com'
    $Capture.Value = $s.Value
})
$b # => john.doe@testdomain.com
$Capture.Value # => @domain.com

This what I could think using only -replace, adding a delimiter (// in this case) to the replaced string followed by the capture group $0 and then splitting the replacement. Though, this is obviously not a robust solution.

$a = '[email protected]'
$b, $capture = $a -replace "[?=@].*", '@testdomain.com//$0' -split '//'
$b # => john.doe@testdomain.com
$capture # => @domain.com

CodePudding user response:

To change the user part you can replace ^.*(?=@):

PS ~> $a = '[email protected]'
PS ~> $a -replace '^.*(?=@)', 'jane.doe'
[email protected]

The (?=@) construct is known as a lookahead, and describes a zero-length string at the position immediately before the @.

  • Related