KILLADELPHIA
KILLADELPHIA

Reputation: 59

How to Get Regex to Return Digits Before String

Here is my sample string I'm trying to parse with PowerShell using Regex.

04/22/17 19:16:44   77.9    BATT    Min: 00.0   Max: 100.0

Here is my Regex to get the digits:

'\d+\.\d'

What I'm trying to do is get the digits (77.9) before the string (BATT) exclusively. I'm able to get the 77.9 and BATT with:

(\d+\.\d)\s+BATT

I just need the number on it's own though and I'm not sure how to get the correct look ahead to do that.

Upvotes: 0

Views: 129

Answers (2)

Dai
Dai

Reputation: 155145

You don't need a lookahead at all. Your (\d+\.\d)\s+BATT regex is correct, you just need to only select the first group:

$input = "04/22/17 19:16:44   77.9    BATT    Min: 00.0   Max: 100.0"
$match = $input -match "(\d+\.\d)\s+BATT"
if( $match ) {
    $value = $match[1]
    Write-Host $value
}

Gives me this output:

77.9

Upvotes: 2

TessellatingHeckler
TessellatingHeckler

Reputation: 28983

A valid lookahead would be something like "match a number (lookahead which is followed by spaces, then BATT). In this example, looking for "one or more non-spaces" to get the number:

PS C:\> $s = '04/22/17 19:16:44   77.9    BATT    Min: 00.0   Max: 100.0'

PS C:\> $s -match '\S+(?=\s+BATT)'
True

PS C:\> $Matches

Name                           Value                                                                                                                                                                        
----                           -----                                                                                                                                                                        
0                              77.9      

But looking at your data, regex is overkill. It's a date, a time, a number - split it by spaces and take the third thing:

PS C:\> (-split $s)[2]
77.9

And on the topic of regex, I rather like regexes which "replace what you don't want" rather than "match what you do what", because they are a one-step operation and you don't have to deal with matches and group extraction:

PS C:\> $s -replace '.*?(\S+)\s+BATT.*', '$1'
77.9

Upvotes: 2

Related Questions