Reputation: 3511
I have a powershell string which can contain multiple email address, for example below is a exmaple that contains two email ids. In that i have two scenarios.
1) Scenario One where the @gmail.com is consistent
[email protected],[email protected]
2) Secnario second: where the @mail.com could be different
strEmail2 = [email protected],[email protected]
I need to get rid of anything after @ including it.
So for result for
scenario (1) will be: john.roger,smith.david
Scenario (2) will be: john.roger,smith.david
SO for Scenarion(1) i can use replace with "hardcoded" value of "@gmail.com", How about second secnario.
I am looking for some solution which will work for both scenarion... like something in Regex or any other way i don't know.
Upvotes: 1
Views: 227
Reputation: 16116
Another approach... Well, if you like RegEx of course
Clear-Host
$SomeEmailAddresses = @'
1) Scenario One where the @gmail.com is consistent
[email protected],[email protected]
2) Secnario second: where the @mail.com could be different
strEmail2 = [email protected],[email protected]
'@
((((Select-String -InputObject $SomeEmailAddresses `
-Pattern '\w+@\w+\.\w+|\w+\.\w+@\w+\.\w+|\w+\.\w+@\w+\.\w+\.\w+' `
-AllMatches).Matches).Value) -replace '@.*') -join ','
Results
john.roger,smith.david,john.roger,smith.david
Just comment out or delete the -join for one per line
Upvotes: 0
Reputation: 58491
Splitting and joining would return the names on one line
Following
$strEmail = "[email protected],[email protected]"
($strEmail -split "," | % {($_ -split "@")[0]}) -join ","
returns
john.roger,smith.david
Breakdown
$strEmail -split "," returns an array of two elements
[0] [email protected]
[1] [email protected]
% {($_ -split "@")[0]} loops over the array
and splits each item into an array of two elements
[0] john.roger
[1] gmail.com
[0] smith.david
[1] outlook.com
and returns the first element [0] from each array
- join "," joins each returned item into a new string
Upvotes: 3
Reputation: 1922
Both of these should work.
This will print each name on a new line:
$strEmail = "[email protected],[email protected]"
$strEmail = $strEmail.Split(',') | Foreach {
$_.Substring(0, $_.IndexOf('@'))
}
$strEmail
This will give you the same output as you outlined above:
$strEmail = "[email protected],[email protected]"
$strEmailFinal = ""
$strEmail = $strEmail.Split(',') | Foreach {
$n = $_.Substring(0, $_.IndexOf('@'))
$strEmailFinal = $strEmailFinal + $n + ","
}
$strEmailFinal.TrimEnd(',')
Upvotes: 1