正则表达式可以使事情变得更加复杂。这是一个有效的解决方案。也有评论和字符串的解决方案。
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;
}
输出:
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 \"'}
编辑:我们走了。内部字符串问题也解决了。这应该可以替换任何 CSS 属性。再次编辑:为评论添加了修复。