C# .NET - Regular Expression..Needed - Asked By shah zeb on 21-Nov-11 08:32 AM

I need a regular expression in csharp which should replace the string contained in two delimters.
The problem is there may come some nested delimeters.

System.Text.RegularExpressions.Regex.Replace(str , @"!.+?\|", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase  );

Above RE works fine for !(starting delimter) and |(ending delimeter).

if we have no nested delimeters.
When the nested comes problem starts.
How it should be handled?
Regards..
Anil Kumar replied to shah zeb on 21-Nov-11 08:43 AM
Hi Shah,

A simple Regex would be:

string input = "Give [Me Some] Purple (And More) Elephants";
string regex = "(\\[.*\\])|(\".*\")|('.*')|(\\(.*\\))";//you build up your Regex here.
string output = Regex.Replace(input, regex, "");
 It will replace the string with null.

Another code:
string RemoveBetween(string s, char begin, char end)
{
   
Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", begin, end));
   
return regex.Replace(s, string.Empty);
}

string s = "Give [Me Some] Purple (And More) \\Elephants/ and .hats^";
s
= RemoveBetween(s, '(', ')');
s
= RemoveBetween(s, '[', ']');
s
= RemoveBetween(s, '\\', '/');
s
= RemoveBetween(s, '.', '^');
 Use whatever you want to replace instead of empty

Hope it helps you.
Do update us again.
Thank you
Anil