简体   繁体   English

PowerShell 替换正则表达式

[英]PowerShell Replace Regex

I have a select-string which is searching an IIS log for a particular string and returning the 2 lines above and one line below.我有一个select-string ,它在 IIS 日志中搜索特定字符串并返回上面的 2 行和下面的一行。

Results look like this:结果如下所示:

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 - - - - 

Note the third line begins with > denoting that's the line that select-string matched upon.请注意,第三行以>开头,表示这是select-string匹配的行。

I am trying to do a -replace on the > to replace it with < font color="red">$1< /font> but my replace doesn't seem to work.我正在尝试在>上执行-replace以将其替换为< font color="red">$1< /font>但我的替换似乎不起作用。

Here's my code:这是我的代码:

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

Can any PowerShell regex gurus out there tell me why my regular expression isn't matching?任何 PowerShell 正则表达式专家都可以告诉我为什么我的正则表达式不匹配吗?

If $a contains the value of your third line try :如果 $a 包含您的第三行的值,请尝试:

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

Two things :两件事情 :

  1. Use single qutes for your RegEx为您的 RegEx 使用单引号
  2. The index of groups begin at 1组的索引从 1 开始

You should start thinking-object rather than text, because what you see is only formated object, not actual output of select-string.您应该开始思考对象而不是文本,因为您看到的只是格式化的对象,而不是选择字符串的实际输出。 Instead of parsing this output - use objects that you get (Get-Member will let you discover them).而不是解析这个输出 - 使用你得到的对象(Get-Member 会让你发现它们)。

I guess this should do what you need:我想这应该做你需要的:

# 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 Bartek HTH 巴特克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM