$sql = @"
use database_instance
go
if condition
"@
$sql -ireplace 'use\s+\w+_\w+\s*(?:\r?\n)+\s*go' , ''
How this Works:
- Using
-ireplace
for case insensitive regex.
- Find the word
use
followed by one or more whitespace \s+
followed by one or more word characters \w+
, then an underscore _
.
- One or more word characters
\w+
, followed by 0 or more whitespace (just in case)
- A non-capturing group
(?:)
since we don't need the result, this is just to encapsulate a newline that accounts for windows and unix line endings. It consists of an optional CR followed by a LF, and this is matched 1 or more times.
- Followed by 0 or more whitespace
\s*
then the word go
.
- Replace it with nothing!
This does leave some empty space, but that shouldn't be too big of an issue since the SQL parser won't care.
Note
In your comments you said you tried:
$out -replace "/use database_\w+\n\w+/g"
Be aware that powershell does not use /regexhere/
syntax. The forward slashes are treated as literals, so the flags you specified are as well. The replace is global by default so you don't need g
anyway.