Powershell ignores the look behind the regex to return the entire string

A fairly simple question that I hope for.

I have a text log file that includes the following line:

123.010502500114082000000009260000000122001T

I want to search the log file and return the "00000000926" section of the above text. Therefore, I wrote a regular expression: (& L;?. = 123 {17}). {eleven}

So, when the appearance of the text is β€œ123” with 17 characters, return the next 11. This works great when testing in online regular expression editors. However, in Powershell, the entire string is returned instead of the 11 characters that I want, and I cannot understand why.

$InputFile = get-content logfile.log $regex = '(?<=123.{17}).{11}' $Inputfile | select-string $regex 

(the whole string is returned).

Why does powershell return the entire string?

+6
source share
3 answers

This is because you are using Select-String , which returns a string that matches (think grep ).

 $InputFile = get-content logfile.log | ForEach-Object { if ($_ -match '(?<=123.{17})(.{11})') { $Matches[1] } } 

Did not test this, but it should work (or something similar).

+5
source

Do not decrease Select-String yet. As Briantist says that he does what you want, but you need to extract the data you need in one of two ways. Select-String returns Microsoft.PowerShell.Commands.MatchInfo objects, not just raw strings. We will also use the Select-String feature to directly accept input.

 $InputFile = "logfile.log" $regex = '(?<=123.{17}).{11}' Select-string $InputFile -Pattern $regex | Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value 

If you have at least PowerShell 3.0

 (Select-string $InputFile -Pattern $regex).Matches.Value 

What gives in both cases

 00000009260 
+5
source

You do not need a regular expression for this:

 $InputFile = get-content logfile.log $InputFile -match '123.{28}' -replace '123.{17}(.{11}).+','$1' 
+5
source

Source: https://habr.com/ru/post/985893/


All Articles