使用`提取两个字符串-match`
问题描述:
我试图解析字符串:使用-match
使用`提取两个字符串-match`
helo identity [email protected] Pass (v=spf1)
如下:
$line -match "helo identity (?<sender>.*) (?<heloresult>.*) (v=spf1)"
我认为这将返回:
$matches['sender'] = "[email protected]"
$matches['heloresult'] = "Pass"
但是,它返回$false
。
值得关注的是以下按预期工作:
$line -match "helo identity (?<sender>.*) Pass"
PS C:\> $matches
Name Value
---- -----
sender [email protected]
0 helo identity [email protected] Pass
我在做什么错误分配这两个部分?
答
谈到我的意见为答案requested:
(
和)
是powershell正则表达式的特殊字符。文字括号必须用反斜杠进行转义。在你的情况下,正确的正则表达式是:
helo identity (?<sender>.*) (?<heloresult>.*) \(v=spf1\)
+0
谢谢!这工作! https://gist.github.com/mbrownnycnyc/4ed056431664575a0a77 – mbrownnyc
答
在最后一个v = spf1零件周围绕过捕获圆括号,使它们成为文字圆括号。使用反斜线即正则表达式转义字符进行转义。
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)
我想你应该逃避'括号(V = SPF1)'正确的正则表达式是:'HELO标识( *( *?)? )\(v = spf1 \)' –
fardjad
我同意@fardjad,您应该将其作为答案发布。 – briantist