0

Maybe the question is familiar but I need an explanation in this case.

Let's assume that I have a file called test.txt. It has the following content:

An example of this line. The line has more than 20 characters.
[sql]SELECT * FROM LINE WHERE aLine = '123'[/sql]
blah blah blah blah...

OR what's about

An example of this line. The line has more than 20 characters.
[sql]SELECT * FROM 
       LINE 
     WHERE aLine = '123'[/sql]
blah blah blah blah...

[sql] SELECT * FROM ME[/sql]

 etc..er
[sql]
   SELECT * FROM ALL
 [/sql]

I want to get a string between [sql] and [/sql] delimiters.

How to do that ? With Regular expression ?

Thanks for patience ...

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • 3
    Is there only one instance of the string you need? – scottm Jul 03 '12 at 14:18
  • 1
    **Did you try** starting with a simple IndexOf/Substring pair? Then you can move to something less naive (regex?) in case you need. – Adriano Repetti Jul 03 '12 at 14:20
  • well.. there are a lot of ways. You can find parser libraries on the net for complex things... In your case, if you have only a single tag, you could use IndexOf("[sql]"), IndexOf("[/sql]") and subString – Kek Jul 03 '12 at 14:21

4 Answers4

2

You can use the same solution found in this answer

string ExtractString(string s, string tag) {
     // You should check for errors in real-world code, omitted for brevity
     var startTag = "[" + tag + "]";
     int startIndex = s.IndexOf(startTag) + startTag.Length;
     int endIndex = s.IndexOf("[/" + tag + "]", startIndex);
     return s.Substring(startIndex, endIndex - startIndex);
}
Community
  • 1
  • 1
Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126
1
int start = foo.IndexOf("[sql]") + 5;

var sql = foo.SubString(start, foo.IndexOf("[/sql]") - start - 5);
Alex
  • 34,899
  • 5
  • 77
  • 90
0

If there is only one occurance, you can use common string operators:

string str = File.ReadAllText(@"c:\test.txt");

int start = str.IndexOf("[sql]");
int end = str.IndexOf("[/sql]");
string sql = str.Substring(start + 5, end - start - 5);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

An old question but this often pops up on a Google query about searching for delimited strings. I found a good solution in

Regex: C# extract text within double quotes

in "Bart's" answer.

It's a Linq-based solution. You split the string using your delimiter character as the split character. Then you keep all the odd-numbered entries.

var stringArray = str.Split('"').Where((item, index) => index % 2 != 0);

In my case I was looking for strings delimited by a dollar sign, '$'. Example: $WantThisString$. Worked like a champ. Thanks Bart!

CLSnyder
  • 111
  • 1
  • 4