我们来看看这段代码:
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"
有人可以帮忙解决这个问题吗?我没有找到任何解释它的文件。
答案 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);