kusanagi
kusanagi

Reputation: 14624

question about regex

i'v got code

s = Regex.Match(item.Value, @"\/>.*?\*>", RegexOptions.IgnoreCase).Value;

it returns string like '/>test*>', i can replace symbols '/>' and '*>', but how can i return string without this symbols , only string 'test' between them?

Upvotes: 2

Views: 65

Answers (3)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

You can group patterns inside the regx and get those from the match

var    match= Regex.Match(item.Value, @"\/>(?<groupName>.*)?\*>", RegexOptions.IgnoreCase);
 var data= match.Groups["groupName"].Value

Upvotes: 2

Richard Nienaber
Richard Nienaber

Reputation: 10564

You can also use look-ahead and look-behind. For your example it would be:

var value = Regex.Match(@"(?<=\/>).*?(?=\*>)").Value;

Upvotes: 1

jb.
jb.

Reputation: 10351

You can save parts of the regex by putting ()'s around the area. so for your example:

// item.Value ==  "/>test*>"
Match m = Regex.Match(item.Value, @"\/>(.*?)\*>");
Console.WriteLine(m.Groups[0].Value); // prints the entire match, "/>test*>"
Console.WriteLine(m.Groups[1].Value); // prints the first saved group, "test*"

I also removed RegexOptions.IgnoreCase because we aren't dealing with any letters specifically, whats an uppercase /> look like? :)

Upvotes: 2

Related Questions