C# Regex如何获取url()内容
大家好,我正试图用正则表达式解析css url,但一切都失败了C# Regex如何获取url()内容,c#,css,regex,url,C#,Css,Regex,Url,大家好,我正试图用正则表达式解析css url,但一切都失败了 Regex cssUrls = new Regex(@"url\((?<char>['""])?(?<url>.*?)\k<char>?\)"); foreach (var item in cssUrls.Matches("@import url(pepe/global.css);")) { MessageBox.Show(item.ToString()); } Regex cssU
Regex cssUrls = new Regex(@"url\((?<char>['""])?(?<url>.*?)\k<char>?\)");
foreach (var item in cssUrls.Matches("@import url(pepe/global.css);"))
{
MessageBox.Show(item.ToString());
}
Regex cssUrls=new Regex(@“url\(?[”)?(?*?)\k?\);
foreach(cssUrls.Matches(@import url(pepe/global.css);)中的var项)
{
Show(item.ToString());
}
输出是:url(pepe/global.css)
但我需要:pepe/global.css
提前谢谢 cssUrls.Matches中的
Matches
对象包含所有匹配的字符串,因此item.ToString()给出整个匹配。您需要类似于item.Groups[“url”].Value的内容来仅提取匹配的url
命名部分。可能的替代解决方案,部分使用正则表达式和字符串操作实现
Regex cssUrls = new Regex(@"\(['"]?(?<url>[^)]+?)['"]?\)");
foreach (var item in cssUrls.Matches("@import url(pepe/global.css);"))
{
MessageBox.Show(item.TrimStart("(").TrimEnd(")").ToString());
}
Regex cssUrls=新的正则表达式(@“\(['”]?(?[^)]+?)['”]?\);
foreach(cssUrls.Matches(@import url(pepe/global.css);)中的var项)
{
MessageBox.Show(item.TrimStart(“(”).TrimEnd(“)”).ToString();
}
item没有“groups”属性。在foreach
声明中将您的var
更改为Match
,这样它就知道item
将是Match
。这不是问题,这就是为什么。有点奇怪,它没有检测到项目将是匹配
,我想这是因为MatchCollection实现了IEnumerable
,而不是IEnumerable
。