Match everything between two words in Powershell

前端 未结 3 1850
刺人心
刺人心 2021-01-03 16:37

I have a big text file with SQL query in between blocks of EXEC SQL --- END-EXEC.

I need everything in-between EXEC SQL --- END-EXEC. keywords. Sample Input is below

相关标签:
3条回答
  • 2021-01-03 17:10

    You need to use a lazy quantifier to make sure that your regex matches each EXEC block individually. And you can gather all matches with a single regex operation:

    $regex = [regex] '(?is)(?<=\bEXEC SQL\b).*?(?=\bEND-EXEC\b)'
    $allmatches = $regex.Matches($subject);
    

    Explanation:

    (?is)         # Case-insensitive matching, dot matches newline
    (?<=          # Assert that this matches before the current position:
     \b           # Start of a word
     EXEC\ SQL    # Literal text "EXEC SQL"
     \b           # End of word
    )             # End of lookbehind assertion
    .*?           # Match any number of characters, as few as possible
    (?=           # until it's possible to match the following at the current position:
     \bEND-EXEC\b # the words "END-EXEC"
    )             # End of lookahead assertion
    
    0 讨论(0)
  • 2021-01-03 17:22

    Or:

    (?<=\*\*EXEC SQL\*\*)[\s\S]*(?=\*\*END-EXEC\*\*)
    

    With multiline mode

    0 讨论(0)
  • 2021-01-03 17:26
    $script = Get-Content D:\temp\script.sql
    
    $in = $false
    
    $script | %{
        if ($_.Contains("EXEC SQL"))
            { $in = $true }
        elseif ($_.Contains("END-EXEC"))
            { $in = $false; }
        elseif ($in)
            { Write-Host $_ } # Or Out-File ...
    }
    
    0 讨论(0)
提交回复
热议问题