Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

powershell How to capture 'left side' of the -replace regex?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$a = 'john.doe@domain.com'
$b = $a -replace "[?=@].*", '@testdomain.com'
$b
john.doe@testdomain.com

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

>Solution :

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 = 'john.doe@domain.com'
$Capture = @{}

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading