Search code examples
c#regexstring-literals

Capture variable string in a regular expression?


In C#, I'm attempting to use the following capture pattern with a variable - I wonder if I'm going about this wrong. info_name is a string variable I pass to the method.

    Regex g = new Regex(@"""" + info_name + """>.+</span>");
    // capture "info">Capture pattern</span>

But it gives me an error, ')' expected about halfway through. This gives no error:

    Regex g = new Regex(@"""" + info_name +">.+</span>");
                                         //^ 1 quote, not 3

I can't use this as a solution, I need to capture the " just before the close of the tag.


Solution

  • You're using two string literals there, so you need to apply the @ both times:

    Regex g = new Regex(@"""" + info_name + @""">.+</span>");
    
    // or alternatively
    Regex g = new Regex("\"" + info_name + "\">.+</span>");