[英]Regex doesn't match in C#
I have an ASP.net string, and I am trying to extract ID from it. 我有一个ASP.net字符串,并且正在尝试从中提取ID。 Here is the code:
这是代码:
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;
}
And regex.IsMatch(line) always returns false. regex.IsMatch(line)始终返回false。
You didn't do the grouping at your regex. 您没有在正则表达式中进行分组。 Here it is
这里是
var regex = new Regex("/.*ID=\"(.*?)\".*/g");
^ ^
Update: The way you are matching the regex is not correct. 更新:匹配正则表达式的方式不正确。 Here is how it works.
下面是它的工作原理。
var regex = "ID=\"(.*?)\"";
if ( Regex.IsMatch(line, regex) ){
ret = Regex.Match(line, regex).Groups[1].Value;
}
Solved it. 解决了。 Workiing code is :
工作代码为:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.