Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern for text between 2 strings

Tags:

c#

regex

I am trying to extract all of the text (shown as xxxx) in the follow pattern:

Session["xxxx"]

using c#

This may be Request.Querystring["xxxx"] so I am trying to build the expression dynamically. When I do so, I get all sorts of problems about unescaped charecters or no matches :(

an example might be:

string patternstart = "Session[";
string patternend = "]";
string regexexpr = @"\\" + patternstart + @"(.*?)\\" + patternend ;
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";

MatchCollection matches = Regex.Matches(sText, @regexexpr);

Can anyone help with this as I am stumped (as I always seem to be with RegEx :) )

like image 829
spanout Avatar asked Sep 03 '13 21:09

spanout


2 Answers

With some little modifications to your code.

string patternstart = Regex.Escape("Session[");
string patternend = Regex.Escape("]");
string regexexpr = patternstart + @"(.*?)" + patternend;
like image 85
I4V Avatar answered Sep 17 '22 06:09

I4V


The pattern you construct in your example looks something like this:

\\Session[(.*?)\\]

There are a couple of problems with this. First it assumes the string starts with a literal backslash, second, it wraps the entire (.*?) in a character class, that means it will match any single open parenthesis, period, asterisk, question mark, close parenthesis or backslash. You'd need to escape the the brackets in your pattern, if you want to match a literal [.

You could use a pattern like this:

Session\[(.*?)]

For example:

string regexexpr = @"Session\[(.*?)]";
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";

MatchCollection matches = Regex.Matches(sText, @regexexpr);
Console.WriteLine(matches[0].Groups[1].Value); // "xxxx"
like image 35
p.s.w.g Avatar answered Sep 21 '22 06:09

p.s.w.g