繁体   English   中英

Powershell字符串操作和替换

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM