[英]Powershell string manipulation and replace
我有一個可以包含多個電子郵件地址的powershell字符串,例如,下面是一個包含兩個電子郵件ID的示例。 在這種情況下,我有兩種情況。
1) Scenario One where the @gmail.com is consistent
strEmail=john.roger@gmail.com,smith.david@gmail.com
2) Secnario second: where the @mail.com could be different
strEmail2 = john.roger@gmail.com,smith.david@outlook.com
我需要清除@之后的所有內容。
So for result for
scenario (1) will be: john.roger,smith.david
Scenario (2) will be: john.roger,smith.david
所以對於Scenarion(1),我可以使用替換為“ @ gmail.com”的“硬編碼”值,第二個密碼如何。
我正在尋找一些適用於這兩種情況的解決方案...就像正則表達式中的某些內容或我不知道的其他任何方式。
拆分和合並將在一行上返回名稱
以下
$strEmail = "john.roger@gmail.com,smith.david@outlook.com"
($strEmail -split "," | % {($_ -split "@")[0]}) -join ","
退貨
john.roger,smith.david
分解
$strEmail -split "," returns an array of two elements
[0] john.roger@gmail.com
[1] smith.david@outlook.com
% {($_ -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
這兩個都應該起作用。
這將在新行上打印每個名稱:
$strEmail = "john.roger@gmail.com,smith.david@outlook.com"
$strEmail = $strEmail.Split(',') | Foreach {
$_.Substring(0, $_.IndexOf('@'))
}
$strEmail
這將為您提供與上述相同的輸出:
$strEmail = "john.roger@gmail.com,smith.david@outlook.com"
$strEmailFinal = ""
$strEmail = $strEmail.Split(',') | Foreach {
$n = $_.Substring(0, $_.IndexOf('@'))
$strEmailFinal = $strEmailFinal + $n + ","
}
$strEmailFinal.TrimEnd(',')
另一種方法...好吧,如果您當然喜歡RegEx
Clear-Host
$SomeEmailAddresses = @'
1) Scenario One where the @gmail.com is consistent
strEmail=john.roger@gmail.com,smith.david@gmail.com
2) Secnario second: where the @mail.com could be different
strEmail2 = john.roger@gmail.com,smith.david@outlook.com
'@
((((Select-String -InputObject $SomeEmailAddresses `
-Pattern '\w+@\w+\.\w+|\w+\.\w+@\w+\.\w+|\w+\.\w+@\w+\.\w+\.\w+' `
-AllMatches).Matches).Value) -replace '@.*') -join ','
結果
約翰·羅傑,史密斯·大衛,約翰·羅傑,史密斯·大衛
只需注釋掉或刪除-join每行一個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.