How to replace a string from certain position to another?

I am trying to replace all the urls from a file with others

To this end I do something like this:

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

I DON’T want to just replace all the strings from a certain index, I want to replace from one index to another all the chars in between. How can I do this?

Upvotes: 0

Views: 133

Answers (4)

gpmurthy
gpmurthy

Reputation: 2427

Conisder using Regex.Replace as follows...

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

Good Luck!

Upvotes: 1

Sid
Sid

Reputation: 317

Using string format.

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

Upvotes: 0

helb
helb

Reputation: 7783

You may want to declare prefix/postfix

string prefix = "url(\"";
string postfix = ".png)";

and then

// replace urls
newLine = line.Substring(0, startPosition) + prefix + newUrl + postfix
    + line.Substring(endPosition + posfix.Length);
// todo: put newLine in result, e.g. List<string>

So you will end up with something like:

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

Upvotes: 1

jasonnissen
jasonnissen

Reputation: 156

One option is to read the CSS contents from the file and call Replace:

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

Upvotes: 0

Related Questions