tags:

views:

400

answers:

2

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 result with RegEx?

+1  A: 

Match your string agains "--ignore.+--endignore" and use string.replace to replace it with string.empty.

Mehran
can you post a little code example if you don't mind. thank you.
gsharp
+3  A: 

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.

Jon Skeet
Thanks for your help. I still have a problem if there is more than one --ignore/--endignore block.
gsharp
Oops, yes. Fixed now to make the `.*` reluctant.
Jon Skeet
What about Environment.NewLine ?
Petar Petrov
@Petar: That just determines the line separator for the current operating system - which may not be the line separator used in the file.
Jon Skeet
@Jon. Works fine now. Thanks you are my hero :-p
gsharp
@Jon: True. I suppose the file is created on the same machine ;)
Petar Petrov