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
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
Or:
(?<=\*\*EXEC SQL\*\*)[\s\S]*(?=\*\*END-EXEC\*\*)
With multiline mode
$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 ...
}