gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:06:14 25 4
gpt4 key购买 nike

让我们来看看这段代码:

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"

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

最佳答案

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

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

关于C# - 如果不在引号内则替换正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23763056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com