簡體   English   中英

如何將字符串從某個位置替換為另一個位置?

[英]How to replace a string from certain position to another?

我試圖將文件中的所有網址替換為其他網址

為此我做了這樣的事情:

 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++;
    }
}

我不想只是從某個索引替換所有字符串,我想從一個索引替換到另一個索引之間的所有字符。 我怎樣才能做到這一點?

您可能需要聲明前綴/后綴

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)
    }
}

使用Regex.Replace的Conisder如下......

string output = Regex.Replace(input, "(?<=url(\).*?(?=.png)", replaceText);

祝好運!

一種選擇是從文件中讀取CSS內容並調用Replace:

var cssContent = File.ReadAllText("styles.css");
cssContent = cssContent.Replace("url('../images/", "url('../content/");
File.WriteAllText("styles.css", cssContent);

使用字符串格式。

 string newLine = String.Format ("{0}{1}{2}{3}{4}",line.Substring(0, startPosition),prefix, newUrl,postfix,line.Substring(endPosition + posfix.Length));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM