Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式在C中不匹配_C#_.net_Regex - Fatal编程技术网

C# 正则表达式在C中不匹配

C# 正则表达式在C中不匹配,c#,.net,regex,C#,.net,Regex,我有一个ASP.net字符串,我正试图从中提取ID。 代码如下: public static string getName(string line) { string ret = ""; if (!line.Contains("ID=")) return ret; var regex = new Regex("/.*ID=\".*?\".*/g"); if (regex.IsMatch(line)) ret = regex.Mat

我有一个ASP.net字符串,我正试图从中提取ID。 代码如下:

public static string getName(string line)
{
    string ret = "";

    if (!line.Contains("ID="))
        return ret;
    var regex = new Regex("/.*ID=\".*?\".*/g");
    if (regex.IsMatch(line))
        ret = regex.Match(line).Groups[1].Value;
    return ret;
}

并且regex.IsMatchline始终返回false。

您没有在regex上进行分组。给你

var regex = new Regex("/.*ID=\"(.*?)\".*/g");
                               ^   ^
更新:您匹配正则表达式的方式不正确。下面是它的工作原理

var regex = "ID=\"(.*?)\"";
if ( Regex.IsMatch(line, regex) ){
    ret = Regex.Match(line, regex).Groups[1].Value;
}

你没有在正则表达式中进行分组。给你

var regex = new Regex("/.*ID=\"(.*?)\".*/g");
                               ^   ^
更新:您匹配正则表达式的方式不正确。下面是它的工作原理

var regex = "ID=\"(.*?)\"";
if ( Regex.IsMatch(line, regex) ){
    ret = Regex.Match(line, regex).Groups[1].Value;
}

解决了。工作代码为:

public static string getName(string line)
        {
            string ret = "";

            if (!line.Contains("ID="))
                return ret;
            var regex = ".*ID=\"(.*?)\".*";
            if (Regex.IsMatch(line, regex) )
                ret = Regex.Match(line, regex).Groups[1].Value;
            return ret;
        }

解决了。工作代码为:

public static string getName(string line)
        {
            string ret = "";

            if (!line.Contains("ID="))
                return ret;
            var regex = ".*ID=\"(.*?)\".*";
            if (Regex.IsMatch(line, regex) )
                ret = Regex.Match(line, regex).Groups[1].Value;
            return ret;
        }

如果正则表达式不起作用,您可以添加一个示例?例如,此行:如果正则表达式不起作用,您可以添加一个示例?例如,此行: