我想从PowerShell中的字符串中解析出电子邮件地址。
例如,给定:
$email = "take this email test@mail.com"
$email2 = "secondmail@mail.com"
$email3 = "thirdmail@mail.com needs extracted"
我会得到:
test@mail.com
secondmail@mail.com
thirdmail@mail.com
所有这些字符串中的域都是相同的,它将始终是username@mail.com地址。
感谢您的帮助!
答案 0 :(得分:0)
您可以使用此正则表达式为您的特定域名提取电子邮件。
\w+@mail.com
只要电子邮件中的用户名部分仅包含字母,数字和下划线即可。否则,您可能不必编写\ w这样的字符类,
[a-zA-Z0-9_.-]+@mail.com
就像您看到的那样,它包含字母,数字,破折号,点,连字符
答案 1 :(得分:0)
受此答案启发
How to validate an email address using a regular expression?
和这个答案
Powershell: Extract text from a string
这将帮助...。
$email = "take this email test@mail.com"
$email2 = "secondmail@mail.com"
$email3 = "thirdmail@mail.com needs extracted"
$email4 = "fourthmail@mail.com and fifthmail@mail.com and sixthmail@mail.com"
$email_regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|`"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*`")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"
$extracted = [regex]::match($email, $email_regex).Value
$extracted
$extracted = [regex]::match($email2, $email_regex).Value
$extracted
$extracted = [regex]::match($email3, $email_regex).Value
$extracted
[regex]::matches($email4, $email_regex)|select value
最后一行显示了如何从一个文本中提取更多电子邮件
答案 2 :(得分:0)
这是另一种方式:
$email = "take this email test@mail.com"
$email2 = "secondmail@mail.com"
$email3 = "thirdmail@mail.com needs extracted"
$array = @($email,$email2,$email3)
foreach($a in $array){
$split = $a.Split(" ")
$email = ($split | ? {$_ -match "@"})
$email
}
答案 3 :(得分:0)
这在PS中应该非常简单;
# initialize your string and pattern (you can choose your own pattern)
$message = "I'm a creep.1990_radio@gmail.com, I'm a wierdo_head@gmail.com"
$pattern = "([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})"
# get all the matches and store it in an array
$results = ($message | Select-String $pattern -AllMatches).Matches
# iterate over array to act on those items
foreach ($item in ($results)) { Write-Host $item.Value }
在最后一行,您还可以使用Write-Host $item
查看可用属性。