0

Solution was adding (?ms) to the front of my regex query

I am trying to search for chunks of text within a file, and preserving the line breaks in a chunk.

When I define my variable as $variable = get-content $fromfile, my function (below) is able to find the text I'm looking for but it is difficult to parse further due to a lack of line breaks

function FindBetween($first, $second, $importing){

    $pattern = "$first(.*?)$second"
    
    $result = [regex]::Match($importing, $pattern).Groups[1].Value

    return $result
}

when I define my variable as $variable = get-content $fromfile -raw, the output of my query is blank. I'm able to print the variable, and it does preserve the line breaks.

I run into the same issue regardless of if I add \r\n to the end of my pattern, if I use @() around my variable definition, if I use -Delimiter \n, or any combination of all those.

Whole code is here:

param($fromfile)

$working = get-content $fromfile -raw

function FindBetween($first, $second, $importing){

    $pattern = "(?ms)$first(.*?)$second"
    
    $result = [regex]::Match($importing, $pattern).Groups[1].Value
    #$result = select-string -InputObject $importing -Pattern $pattern

    return $result
}


FindBetween -first "host ####" -second "#### flag 2" -importing $working | Out-File "testresult.txt"

the file I'm testing it against looks like:

#### flag 1 host ####

stuff in between

#### flag 2 server ####

#### process manager ####



As to why I'm doing this:
I'm trying to automate taking a file that has defined sections with titles and outputting the content of those separate sections into a .csv (each section is formatted drastically different from each other). These files are all uniform to each other, containing the same sections and general content.

Alex Smith
  • 11
  • 3

1 Answers1

0

If you're doing -raw you probably need to change your RegEx to "(?ms)$first(.*?)$second" so that . will match new lines.

TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
  • Worth noting that it is `(?s)` that is crucial here (to make `.` match newlines too and therefore make `.*?` match _across lines_). You only need `(?m)` if you need `^` and `$` to match on _each line_. – mklement0 Sep 22 '22 at 19:56
  • 1
    Yes, excellent point. I never remember which one's which so I usually just include both of them. Thank you for the clarity! – TheMadTechnician Sep 22 '22 at 22:24