正则表达困扰C#

Mik*_*ike 1 .net c# windows

尝试使用以下正则表达式时遇到问题:

string profileConfig = File.ReadAllText(str);

string startIndex = "user_pref(\"network.proxy.autoconfig_url\", \"";
string endIndex = "\"";

var regex = startIndex + "(.*)" + endIndex;
// Here we call Regex.Match.
Match match = Regex.Match(profileConfig, 
                          regex,
                          RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{
    // Finally, we get the Group value and display it.
    string key = match.Groups[1].Value;
    MessageBox.Show(key);
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

附加信息:解析"user_pref("network.proxy.autoconfig_url","(.*)"" - 还不够).

我的正则表达式在某种程度上是否格式错误?

Bar*_*aye 8

如果您想要字符匹配字符,请转义第一个括号(:

string startIndex = "user_pref\\(\"network.proxy.autoconfig_url\", \"";
Run Code Online (Sandbox Code Playgroud)

  • 而不是逃避自己,尝试使用Regex.Escape(startIndex). (2认同)