我正在尝试将文件中的所有网址替换为其他网址
为此,我做了类似的事情:
private static void findAndReplaceImgURLs(string s)
{
var server = HttpContext.Current.Server;
var cssLines = File.ReadLines(server.MapPath(s));
int indexer = 0;
foreach (string line in cssLines)
{
int startPosition = line.IndexOf("url(\"");
int endPosition = line.IndexOf(".png)");
if (startPosition != -1 && endPosition != -1)
{
//replace urls
}
indexer++;
}
}
我不想只是从某个索引替换所有字符串,我想从一个索引替换到另一个索引之间的所有字符。我怎么能这样做?
答案 0 :(得分:1)
您可能需要声明前缀/后缀
string prefix = "url(\"";
string postfix = ".png)";
然后
// replace urls
newLine = line.Substring(0, startPosition) + prefix + newUrl + postfix
+ line.Substring(endPosition + posfix.Length);
// todo: put newLine in result, e.g. List<string>
所以你最终会得到类似的东西:
var result = new List<string>();
foreach (string line in cssLines)
{
string prefix = "url(\"";
string postfix = ".png)";
int startPosition = line.IndexOf(prefix);
int endPosition = line.IndexOf(postfix);
if (startPosition != -1 && endPosition != -1)
{
//replace urls
string newLine = line.Substring(0, startPosition) + prefix + newUrl
+ postfix + line.Substring(endPosition + posfix.Length);
result.Add(newLine)
}
}
答案 1 :(得分:1)
使用Regex.Replace的Conisder如下......
string output = Regex.Replace(input, "(?<=url(\).*?(?=.png)", replaceText);
祝你好运!
答案 2 :(得分:0)
一种选择是从文件中读取CSS内容并调用Replace:
var cssContent = File.ReadAllText("styles.css");
cssContent = cssContent.Replace("url('../images/", "url('../content/");
File.WriteAllText("styles.css", cssContent);
答案 3 :(得分:0)
使用字符串格式。
string newLine = String.Format ("{0}{1}{2}{3}{4}",line.Substring(0, startPosition),prefix, newUrl,postfix,line.Substring(endPosition + posfix.Length));