Powershell取代正则表达式

时间:2012-06-18 00:16:31

标签: regex powershell replace

我有一个select-string,它为特定的字符串搜索IIS日志,并返回上面的2行和下面的一行。所以结果如下:

2012-06-15 18:26:09 98.138.206.39 OutboundConnectionResponse SMTPSVC1 WEB10 - 25 - - 220+mta1083.sbc.mail.ne1.yahoo.com+ESMTP+YSmtp+service+ready 0 0 60 0 218 SMTP - - - -
2012-06-15 18:26:09 98.138.206.39 OutboundConnectionCommand SMTPSVC1 WEB10 - 25 EHLO - WEB10.DOMAIN>COM 0 0 4 0 218 SMTP - - - -
> 2012-06-15 18:26:09 74.125.244.10 OutboundConnectionResponse SMTPSVC1 WEB10 - 25 - - 550+IP+Authorization+check+failed+-+psmtp 0 0 41 0 218 SMTP - - - -
2012-06-15 18:26:09 74.125.244.10 OutboundConnectionCommand SMTPSVC1 WEB10 - 25 RSET - - 0 0 4 0 218 SMTP - - - - 

注意第三行以>开头表示那是select-string匹配的行。

我正试图在>上做一个替换。用&替换它font color =“red”> $ 1< /字体>但我的替换似乎不起作用。

这是我的代码:

$results = $results -replace "(^> )(.*)$", "< font color='red'>$1< font>" 

任何powershell正则表达式大师都可以告诉我为什么我的正则表达式不匹配?

由于 布拉德

2 个答案:

答案 0 :(得分:1)

如果$ a包含第三行的值,请尝试:

$a -replace '(^>)(.*)','font color="red">$2<font/>'

两件事:

  1. 为您的RegEx使用单个qutes
  2. 组的索引从1开始

答案 1 :(得分:1)

你应该开始思考对象而不是文本,因为你看到的只是格式化对象,而不是select-string的实际输出。 而不是解析此输出 - 使用您获得的对象(Get-Member将让您发现它们)。

我想这应该做你需要的:

# Prepare test data...
$tring = @'
alfa
beta
gamma
delta
alfa
beta
alfa
beta
'@.Split("`n")

# Display results with actually matching line highlighted in red...
"<body>"
$tring | select-string 'delta' -Context 2,2 | foreach {
    $_.Context.PreContext
    "<font color='red'>$($_.Line)<font>"
    $_.Context.PostContext
}
"</body>"

HTH 鲍尔泰克

相关问题