C# - 正则表达式替换,如果不在引号内

时间:2014-05-20 14:46:12

标签: c# regex string replace

我们来看看这段代码:

string Val = "I like foo, baz and bar, they where before \"foo, baz and bar\"";

string[] first = {
    "foo",
    "baz",
    "bar"
};

string[] second = {
    "java",
    "php",
    "ruby"
};

看看在我的Val字符串中我有一个文本,我想只替换不在引号(\“)内的部分,但如果我这样做

Val = Regex.Replace(Val, first, second);

它只是给了我

I like java, php and ruby, they where before "java, php and ruby"

虽然我期待

I like java, php and ruby, they where before "foo, baz and bar"

有人可以帮忙解决这个问题吗?我没有找到任何解释它的文件。

1 个答案:

答案 0 :(得分:3)

您可以拆分引号并对每个其他字符串执行替换,然后将字符串放在一起:

string[] parts = Val.Split('"');
for (int i = 0; i < parts.Length; i += 2) {
  parts[i] = Regex.Replace(parts[i], first, second);
}
Val = String.Join("\"", parts);