1

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?

7
  • Could you provide some more exact specs and examples? Certainly, sounds like the simplest is @"\*\*(.*?)\*\*", but the most efficient is@"\*\*([^*]*(?:\*(?!\*)[^*]*)*)\*\*" Commented Aug 3, 2016 at 9:18
  • Define "does not work", what does it do? Commented Aug 3, 2016 at 9:20
  • Why ([^)]*) inside? Do you mean you want to exclude any ) in between **s? Commented Aug 3, 2016 at 9:22
  • @WiktorStribiżew that was it :D I just have to put a \ before every character. Thank you Commented Aug 3, 2016 at 9:22
  • @WiktorStribiżew no I do not, I am not good in regex this is code from all around the web Commented Aug 3, 2016 at 9:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This is it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.