brandeded
brandeded

Reputation: 2199

Extracting two strings using `-match`

I am attempting to parse the string:

helo identity [email protected] Pass (v=spf1)

using -match as follows:

$line -match "helo identity (?<sender>.*) (?<heloresult>.*) (v=spf1)"

I would think this would return:

$matches['sender'] = "[email protected]"
$matches['heloresult'] = "Pass"

However, it returns $false.

Worth noting that the following works as expected:

$line -match "helo identity (?<sender>.*) Pass"
PS C:\> $matches
Name                           Value
----                           -----
sender                         [email protected]
0                              helo identity [email protected] Pass

What am I doing incorrectly to assign these two parts?

Upvotes: 0

Views: 86

Answers (2)

Joakim
Joakim

Reputation: 61

Escape the capturing parentheses around the last v=spf1 part to make them literal parentheses. Escape using a backslash, the regex escape character.

PS C:\temp> 'helo identity [email protected] Pass (v=spf1)' -match 'helo identity (?<Sender>.*) (?<HeloResult>.*) \(v=spf1\)'
True

PS C:\temp> $Matches.Values
[email protected]
Pass
helo identity [email protected] Pass (v=spf1)

Upvotes: 3

fardjad
fardjad

Reputation: 20404

Turning my comment into an answer as requested:

( and ) are special characters in regular expressions. Literal parenthesis must be escaped with backslashes. The correct RegEx in your case would be:

helo identity (?<sender>.*) (?<heloresult>.*) \(v=spf1\)

Upvotes: 2

Related Questions