Capture variable string in a regular expression?

时光总嘲笑我的痴心妄想 提交于 2019-12-24 10:35:50

问题


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.


回答1:


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>");


来源:https://stackoverflow.com/questions/6975949/capture-variable-string-in-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!