Naigel
Naigel

Reputation: 9644

Find all mail address in a file using regex

I need to read with powershell a lot of files and getting all email address. I tried this solution

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

The problem is that the variable $matches contains only the first match. Am I missing something?

Upvotes: 3

Views: 7186

Answers (2)

CodeHeadTheo
CodeHeadTheo

Reputation: 21

The Select-String approach works well here. However, this regex pattern is simply not suitable and you should review the following similar question: Using Regex in Powershell to grab email

Upvotes: 2

Frode F.
Frode F.

Reputation: 54881

-match returns strings with the content, so it works better with a string-array where it can find a match per line. 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.

Try the following:

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

Example:

$myString = @"
[email protected] hhaksda [email protected]
dsajklg [email protected]
"@

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

Groups            Success Captures          Index Length Value
------            ------- --------          ----- ------ -----          
{[email protected]}     True {[email protected]}      0     14 [email protected] 
{[email protected]}    True {[email protected]}    23     15 [email protected]
{[email protected]}    True {[email protected]}    48     15 [email protected]

Upvotes: 5

Related Questions