What regex to use in C# to start matching from a word BEHIND (matching backwards...) until a match?

Let's say a code in HTML:

<a href="http://google.com">this is a search engine</a>"

How to look for "engine" and match anything until "this" gets reached?

I know I can do: this.*?engine - but this is from left to right matching, that is "ahead" matching, here I want to read backwards if this is possible at all?

1 answer

  • answered 2019-12-12 08:04 MichaƂ Turczyn

    You could reverse all strings and perform normal search:

    string text = @"<a href=""http://google.com""> this is a search engine </a>";
    string engine = "engine";
    string strThis = "this";
    new string(
        new string(text.Reverse().ToArray()),
        new string(engine.Reverse().ToArray()) + ".+" + new string(strThis.Reverse().ToArray()))

    Also, to make code clearer, you could define extension method on a string, which reverses string and returns string instead of IEnumerable<char>. See this for reference.