Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.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# Regex如何获取url()内容_C#_Css_Regex_Url - Fatal编程技术网

C# Regex如何获取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

大家好,我正试图用正则表达式解析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 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