C#regex捕获得到两个结果,而不是一个
我想检查URL是否匹配如下模式:C#regex捕获得到两个结果,而不是一个,c#,regex,C#,Regex,我想检查URL是否匹配如下模式:http://the.site.com/some/path/1234567并同时从中提取最后一个数字 如果我这样做: Match m = Regex.Match(url, "^http://the.site.com/some/path/(?<picid>.*?)$"); if (m.Success) { log(string.Format("New download. Id={0}", m.Groups["picid"].Value)); }
http://the.site.com/some/path/1234567
并同时从中提取最后一个数字
如果我这样做:
Match m = Regex.Match(url, "^http://the.site.com/some/path/(?<picid>.*?)$");
if (m.Success)
{
log(string.Format("New download. Id={0}", m.Groups["picid"].Value));
}
Match m=Regex.Match(url,“^http://the.site.com/some/path/(?.*?)$");
如果(m.成功)
{
log(string.Format(“New download.Id={0}”,m.Groups[“picid”].Value));
}
它返回2个组。一个包含
http://the.site.com/some/path/1234567
,另一个1234567
。如何更改正则表达式以仅获取一个捕获-数字?您可以使用正则表达式标志
用法:
Regex.Match(url, "^http://the.site.com/some/path/(?<picid>.*?)$", RegexOptions.ExplicitCapture);
Regex.Match(url,“^http://the.site.com/some/path/(?*?$”,RegexOptions.ExplicitCapture);
您可以使用regex标志
用法:
Regex.Match(url, "^http://the.site.com/some/path/(?<picid>.*?)$", RegexOptions.ExplicitCapture);
Regex.Match(url,“^http://the.site.com/some/path/(?*?$”,RegexOptions.ExplicitCapture);
根据您的示例,您需要检查字符串是否匹配,并从示例中的字符串中获取最后一个数字是7。请执行以下操作:
Match m = Regex.Match(url, @"^http://the.site.com/some/path/\d+$");
if (m.Success)
{
int y = int.Parse(m.Value[m.Value.Length - 1].ToString());
}
根据您的示例,您需要检查字符串是否匹配,并从示例中的字符串中获取最后一个数字是7。请执行以下操作:
Match m = Regex.Match(url, @"^http://the.site.com/some/path/\d+$");
if (m.Success)
{
int y = int.Parse(m.Value[m.Value.Length - 1].ToString());
}
下面的正则表达式应该只捕获数字
(?<=http://the.site.com/some/path/)(?<picid>.*?)$
(?以下正则表达式应仅捕获数字
(?<=http://the.site.com/some/path/)(?<picid>.*?)$
(?第一组始终是整个匹配项;您不能更改它。只需通过指定索引来使用第二组。@acheong87:您是对的,只有第二组具有所需的捕获名称。我很快就忽略了这一点。第一组始终是整个匹配项;您不能更改它。只需通过指定索引来使用第二组。@acheong87:您可以是的,只有第二组有一个想要的捕获名称。我很快忽略了这一点。参考链接的英文版本:参考链接的英文版本: