Search code examples
stringpowershellcomparison-operators

PowerShell, parsing, problem using a specific string with -match/-like and -split


I have a variable that is filled with several lines of text and I am trying to parse the data from it. Now around the middle of the text is a specific string "Reference(s) :" and I need to get everything from above this specific string. However every way I have tried has failed.

I tried making it a delimiter

$Var.split("Reference(s) :")

I tried the below 2 options just to try to capture that one line (because if I can do this, then I know I can pull everything before it).

$Var.split("`n") | Where-Object {$_ -match "Reference(s) :"}

and

$Var.split("`n") | Where-Object {$_ -like "*Reference(s) :*"}

and I've tried some if statements (Where $_ is a single line of text)

If ($_ -like "*Reference(s) :*") {some logic}

I cannot just match "Reference" because that word appears elsewhere in the text....and I am needing this to process several instances of this text.

I think the problem has to do with the parenthesis, the space, and the colon (special characters). I did try preceding each special character with a ` but that did not seem to work.

Anyone have any ideas? There has to be a way to match special characters, I just haven't found it yet.


Solution

  • If $var is truly a single string, you can use -split at your reference point and then retrieve the first split string ([0]). This will retrieve everything from the start of the string until the split point.

    ($Var -split 'Reference\(s\) :')[0]
    

    Since -split uses regex matching, you must backslash escape regex special characters to match them literally. Here ( and ) are special.

    In the future, you can just process your match string using [regex]::Escape('String'), and it will do all the escaping for you.


    If you want the line just before the reference point, you can convert your string into an array. Then return the line above the matching line.

    foreach ($line in ($Var -split '\r?\n')) {
        if ($line -match 'Reference\(s\) :') { 
            $lastLine
        } else { 
            $lastLine = $line
        } 
    }