如何用正则替换css文件路径
例如: <link href="css/main.css" type="text/css" rel="stylesheet">
替换成
<link href="/path1/path2/css/main.css" type="text/css" rel="stylesheet">
请问这样如何替换呢
css
stylesheet
正则
替换
路径
------解决方案-------------------- string str = "<link href=\"css/main.css\" type=\"text/css\" rel=\"stylesheet\">";
str = Regex.Replace(str, @"(?is)(<link[^>]*?href=[""'])([^""']+)([^>]+>)", "$1/path1/path2/$2$3");
------解决方案--------------------(?i)(?<=<link\s*href=")([^"]+?)(?="[^>]*?>)
string str=@"<link href=""css/main.css"" type=""text/css"" rel=""stylesheet"">";
str=Regex.Replace(str,@"(?i)(?<=<link\s*href="")([^""]+?)(?=""[^>]*?>)",@"/path1/path2/css/main.css");
------解决方案-------------------- string tempStr = File.ReadAllText(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312"));//读取txt
string pattern = @"(?i)(?<=<link[^>]*?href=['""])(?:[^/'""]*?/)+([^'""]+?\.[^'""]+?)(?=['""])";
tempStr = Regex.Replace(tempStr, pattern, "/path1/path2/css/$1");
/*
* <link href="/path1/path2/css/main.css" type=""text/css"" rel=""stylesheet"">或者
<link href="/path1/path2/css/main1.css" type=""text/css"" rel=""stylesheet"">又或者
<link href="/path1/path2/css/main2.css" type=""text/css"" rel=""stylesheet"">
*/
//