1

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.

2
  • But be wary of what you pass in in info_name - if it happens to contain any special Regex characters, it may mess up your Regex. Commented Aug 7, 2011 at 21:44
  • @Nikki: Good point. That can be handled using Regex.Escape if necessary. I didn't add that to my own answer because it's possible that info_name has already been pre-processed or suitably sanitised. Commented Aug 7, 2011 at 21:47

1 Answer 1

4

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>");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! For some reason escaping a quote " with \" doesn't work, it stops the expression. I have to use "" to escape it. Your first answer seemed to work! Thanks a bunch! Also, I read why parsing HTML with Regex is an unholy sin like the work of satan, so I might try another way to do this.
Or use new Regex("\"" + info_name + "\">.+</span>"). @ is often used in Regex strings, because Regexes often contain backslash characters, and you have to escape each one with another backslash in regular strings (without the @).
Ah, that's why the \ was cancelling it out. I have a lot to learn. =\

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.