Home > Mobile >  Powershell Regex with special characters
Powershell Regex with special characters

Time:11-23

I am trying to pull info from a log file but can not figure out how to limit the entries to include brackets and two digits in the bracket.

The log file has entries similar to:

11/22/22 11:25:26 RandomUselessData12453: 053, Clen 24, Flen 25, Data: [00] Data: [00 01 23 45 03 15]

I need to pull only the section of Data: [00]

currently using (?:^|\W)data:(.{5})

it is pulling

Data: [00]

Data: [00]

Data: [00 0

Data: [00 0

Full Code currently:

$LogRegexe = '(?:^|\W)data:(.{5})'
$LogLocation = get-content "C:\blah\log.log" -Tail 80

$LogLocation | 
select-string $LogRegexe |
foreach-object { $_.Matches.Value } |
set-content "C:\blah\log.log"

CodePudding user response:

You can use

\bdata:\s*\[(\d{2})]

See the regex demo. Details:

  • \b - a word boundary (much better than (?:^|\W))
  • data: - a fixed string
  • \s* - zero or more whitespaces
  • \[ - a [ char
  • (\d{2}) - Group 1: two digits
  • ] - a ] char.

CodePudding user response:

If you're looking for just Data: [00], you can limit it to search for numbers in brackets with just 2 digits: 'Data: \[\d{2}\]' :

Select-String -Path "C:\blah\log.log" -Pattern 'Data: \[\d{2}\]'| 
    ForEach-Object -Process {
        $_.Matches.Value
    }

Outputs:

Data: [00]
Data: [12]
  • Related