apero apero - 4 months ago 17
C# Question

Extract word out of string using regex

I want to extract certain word out of a string using regex.

I got this code now and it works perfectly when i search for *

public static string Tagify(string value, string search, string htmlTag, bool clear = false)
{
Regex regex = new Regex(@"\" + search + "([^)]*)\\" + search);
var v = regex.Match(value);

if (v.Groups[1].ToString() == "" || v.Groups[1].ToString() == value || clear == true)
{
return value.Replace(search, "");
}

return value.Replace(v.Groups[0].ToString(), "<" + htmlTag + ">" + v.Groups[1].ToString() + "</" + htmlTag + ">");
}


But now I need to search for **, but unfortunately this does not work
How can I achieve this?

Answer

I think the simplest solution is to use lazy dot matching in a capturing group.

Replace

Regex regex = new Regex(@"\" + search + "([^)]*)\\" + search);

with

Regex regex = new Regex(string.Format("{0}(.*?){0}", Regex.Escape(search)));

Or in C#6.0

Regex regex = new Regex($"{Regex.Escape(search)}(.*?){Regex.Escape(search)}");

Regex.Escape will escape any special chars for you, no need to manually append \ symbols.