Regex può rendere le cose molto più complicate. Ecco una soluzione che funziona. Ha anche la soluzione per commenti e stringhe.
static void Main(string[] args)
{
string test = ".white> TD { color: white;box-shadow: 0px 0px 3px white, inset 0px 0px 5px black; white-space:pre-wrap; background-image='white black \" white \"'}";
Console.WriteLine("Before: " + test);
test = replaceInCSS(test, "white", "green");
Console.WriteLine("After: " + test);
Console.ReadLine();
}
static string replaceInCSS(string text, string replace, string replacement)
{
char[] forceBefore = new char[]{ '\n', '\t', ';', '{', ' ', ':', ','};
char[] forceAfter = new char[] { ';', '}', ' ', ','};
int index = text.IndexOf(replace, 0);
while (index != -1)
{
if (!indexWithinStringOrComment(text, index))
{
int afterPos = index + replace.Length;
bool beforeOk = false, afterOk = false;
if (index > 0 && forceBefore.Contains<char>(text[index - 1]))
beforeOk = true;
if (afterPos < text.Length - 1 && forceAfter.Contains<char>(text[afterPos]))
afterOk = true;
if ((index == 0 || beforeOk) &&
(afterPos == text.Length - 1 || afterOk))
{
text = text.Remove(index, replace.Length);
text = text.Insert(index, replacement);
}
}
index = text.IndexOf(replace, index + 1);
}
return text;
}
static bool indexWithinStringOrComment(string text, int index)
{
bool insideStrSimple = false;
bool insideStrDouble = false;
bool insideStrComment = false;
for (int i = 0; i < index; ++i)
{
string subStr = text.Substring(i, 2);
if (text[i] == '\'' && !insideStrDouble && !insideStrComment)
insideStrSimple = !insideStrSimple;
else if (text[i] == '"' && !insideStrSimple && !insideStrComment)
insideStrDouble = !insideStrDouble;
else if (text.Substring(i, 2) == "/*" && !insideStrDouble && !insideStrSimple)
insideStrComment = true;
else if (text.Substring(i, 2) == "*/" && insideStrComment)
insideStrComment = false;
}
return insideStrDouble || insideStrSimple || insideStrComment;
}
uscita:
Before: .white> TD { color: white;box-shadow: 0px 0px 3px white, inset 0px 0px 5px black; white-space:pre-wrap; background-image='white black \" white \"'}
After: .white> TD { color: green;box-shadow: 0px 0px 3px green, inset 0px 0px 5px black; white-space:pre-wrap; background-image='white black \" white \"'}
Edit: Ci andiamo. Anche il problema delle stringhe interne viene risolto. Questo dovrebbe funzionare per sostituire qualsiasi proprietà CSS. Modifica di nuovo: aggiunta correzione per i commenti.
Se si sta facendo questo per rendere il file CSS più piccolo allora andrei fino a suggerire che è una perdita di tempo. Faresti molto meglio semplicemente assicurandoti che il file sia memorizzato nella cache e lasciandolo lì a meno che tu non stia ottenendo enormi quantità di utenti che lo guardano. – Chris