3

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?

2
  • You have another problem you haven't noticed yet - your regex will miss valid email addresses, and probably match invalid ones. It's not a simple regex that matches valid email addresses - and it's a topic that comes up here on SO quite frequently Commented Mar 20, 2013 at 12:40
  • @alroc Thanks for your observation. In fact I'm using a different regex to find email addresses. Here it's only an example, just to understand the problem Commented Mar 20, 2013 at 12:51

2 Answers 2

5

-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]
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.