Reputation: 73
This is a line in a log file:
$line = 'to devices Headset Earphone (Some Device)'
I need the result done with an one liner regex only (if possible):
$result = 'Some Device'
I have it working in two lines:
$InsideLoopLine = [regex]::Matches($Line, '^.*to devices Headset.*$')
[regex]::Matches($InsideLoopLine,'(?<=\().*(?=\))')
New info 1 : @WiktorStribiżew
Code:
$Line = 'to devices Headset Earphone (Some Device)'
([regex]::Matches($Line,'\bto devices Headset.*?\(([^()]+)')).Value
Result:
to devices Headset Earphone (Some Device
New info 2
Code:
$Line = 'to devices Headset Earphone (Some Device)'
([regex]::Matches($Line,'\bto devices Headset.*?\(([^()]+)')).Groups[1].Value
Result:
Some Device
Upvotes: 2
Views: 1864
Reputation: 626699
You may use -match
with a pattern containing a capturing group, then, once there is a match, you may access your expected value using $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
See the regex demo at a .NET regex compatible testing site.
Details
\bto devices Headset
- whole word to
, then space and devices Headset
text.*?
- any 0 or more chars other than a newline, as few as possible\(
- a (
char([^()]+)
- Capturing group 1: any one or more chars other than (
and )
.You may check if there was a match before:
PS C:\Users\admin> $matched = $s -match '\bto devices Headset.*?\(([^()]+)'
PS C:\Users\admin> if ($matched) { Write-Host $matches[1] }
Alternative with [regex]::Match
:
PS C:\Users\admin> $result = [regex]::Match($line, '(?<=\bto devices Headset.*?\()[^()]+').value
PS C:\Users\admin> $result
Some Device
Upvotes: 2
Reputation: 3246
$Query = [regex]::Matches($Line, "to devices Headset Earphone \((.*)\)")
$Query.Groups[1].Value
Upvotes: 1