apero
apero

Reputation: 1164

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?

Upvotes: 1

Views: 108

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

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.

Upvotes: 1

Related Questions