Skip to main content
 首页 » 编程设计

c#之在正则表达式中捕获变量字符串

2024年02月23日22pander-it

在 C# 中,我试图将以下捕获模式与变量一起使用 - 我想知道我是否正在处理这个问题。 info_name 是我传递给方法的字符串变量。

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

但它给了我一个错误,')' 预期大约在中途。这没有错误:

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

我不能将此用作解决方案,我需要在标记结束之前捕获 "。

请您参考如下方法:

你在那里使用了两个字符串文字,所以你需要两次都应用 @:

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