Finding Multiple RegEx Patterns

by Oct 19, 2011

PowerShell comes with great support for regular expressions but the -match operator can only find the first occurrence of a pattern. To find all occurrences, you can use the .NET RegEx type. Here is a sample:

$text = 'multiple emails like and in a string'
$emailpattern = '(?i)\b([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b'

$emails = ([regex]$emailpattern).Matches($text) |
  ForEach-Object { $_.Groups[1].Value }

"*" * 100


Note the statement "(?i)" in the regular expression pattern description. The RegEx object by default works case-sensitive. To ignore case, use this control statement.

Twitter This Tip!
ReTweet this Tip!