[英]Powershell Regular Expression to extract string between rounded parentheses from line in a log file
這是日志文件中的一行:
$line = 'to devices Headset Earphone (Some Device)'
我只需要使用單行正則表達式完成結果(如果可能的話):
$result = 'Some Device'
我有它在兩行工作:
$InsideLoopLine = [regex]::Matches($Line, '^.*to devices Headset.*$')
[regex]::Matches($InsideLoopLine,'(?<=\().*(?=\))')
新信息 1:@WiktorStribiżew
代碼:
$Line = 'to devices Headset Earphone (Some Device)'
([regex]::Matches($Line,'\bto devices Headset.*?\(([^()]+)')).Value
結果:
to devices Headset Earphone (Some Device
新信息 2
代碼:
$Line = 'to devices Headset Earphone (Some Device)'
([regex]::Matches($Line,'\bto devices Headset.*?\(([^()]+)')).Groups[1].Value
結果:
Some Device
$Query = [regex]::Matches($Line, "to devices Headset Earphone \((.*)\)")
$Query.Groups[1].Value
您可以將-match
與包含捕獲組的模式一起使用,然后,一旦匹配,您可以使用$matches[1]
訪問您的預期值:
PS C:\Users\admin> $line = 'to devices Headset Earphone (Some Device)'
PS C:\Users\admin> $s -match '\bto devices Headset.*?\(([^()]+)' | Out-Null
PS C:\Users\admin> $matches[1]
Some Device
請參閱 .NET 正則表達式兼容測試站點上的正則表達式演示。
細節
\bto devices Headset
- 整個單詞to
,然后是空格和devices Headset
文本.*?
- 除換行符以外的任何 0 個或多個字符,盡可能少\(
- 一個(
字符([^()]+)
- 捕獲組 1:除(
和)
之外的任何一個或多個字符。您可以檢查之前是否有匹配:
PS C:\Users\admin> $matched = $s -match '\bto devices Headset.*?\(([^()]+)'
PS C:\Users\admin> if ($matched) { Write-Host $matches[1] }
替代[regex]::Match
:
PS C:\Users\admin> $result = [regex]::Match($line, '(?<=\bto devices Headset.*?\()[^()]+').value
PS C:\Users\admin> $result
Some Device
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.