RegEx search for two pattern strings and cut what's between
I'm trying to write a little SQL Helper. I have a query like this stored in a string:
DECLARE @V1 INT
--ignore
DECLARE @V11 INT
DECLARE @V12 INT
--endignore
DECLARE @V2 INT
--ignore
SELECT * FROM SampleTable
INNER JOIN AnotherSampleTable
......
--endignore
SELECT * From Employee ORDER BY LastName
My helper method should cut everything what's between
--ignore
and
--endignore
The result string should look like:
DECLARE @V1 INT
DECLARE @V2 INT
SELECT * From Employee ORDER BY LastName
How can achieve my resu开发者_C百科lt with RegEx
?
Here's a short example:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
string x = @"
A
--ignore
B
--endignore
C";
Regex regex = new Regex("\r\n--ignore.*?\r\n--endignore\r\n",
RegexOptions.Singleline);
string y = regex.Replace(x, "\r\n");
Console.WriteLine(y);
}
}
Note the use of RegexOptions.Singleline so that .
matches any character including \n
.
I've used Windows line separators here, but you could make the carriage returns optional if you want to be able to cope with Unix separators. I wanted to make sure that the tokens were on their own lines to avoid any rogue references within the SQL, even if that's very unlikely.
Match your string agains "--ignore.+--endignore" and use string.replace to replace it with string.empty.
精彩评论