简体   繁体   English

使用正则表达式查找文件中的所有邮件地址

[英]Find all mail address in a file using regex

I need to read with powershell a lot of files and getting all email address. 我需要使用powershell读取大量文件并获取所有电子邮件地址。 I tried this solution 我试过这个解决方案

$myString -match '\w+@\w+\.\w+'

The problem is that the variable $matches contains only the first match. 问题是变量$matches只包含第一个匹配。 Am I missing something? 我错过了什么吗?

-match returns strings with the content, so it works better with a string-array where it can find a match per line. -match返回带有内容的字符串,因此它更适合使用字符串数组,每行可以找到匹配项。 What you want is a "global" search I believe it's called. 你想要的是一个“全球”搜索我相信它被称为。 In PowerShell you can do that using Select-String with the -AllMatches parameter. 在PowerShell中,您可以使用带有-AllMatches参数的Select-String来完成此-AllMatches

Try the following: 请尝试以下方法:

(Select-String -InputObject $myString -Pattern '\w+@\w+\.\w+' -AllMatches).Matches

Example: 例:

$myString = @"
user@domain.no hhaksda user@domain.com
dsajklg user@domain.net
"@

PS > (Select-String -InputObject $myString -Pattern '\w+@\w+\.\w+' -AllMatches).Matches | ft * -AutoSize

Groups            Success Captures          Index Length Value
------            ------- --------          ----- ------ -----          
{user@domain.no}     True {user@domain.no}      0     14 user@domain.no 
{user@domain.com}    True {user@domain.com}    23     15 user@domain.com
{user@domain.net}    True {user@domain.net}    48     15 user@domain.net

The Select-String approach works well here. Select-String方法在这里运行良好。 However, this regex pattern is simply not suitable and you should review the following similar question: Using Regex in Powershell to grab email 但是,这种正则表达式模式根本不适用,您应该查看以下类似的问题: 在Powershell中使用Regex来抓取电子邮件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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