C# - 如果不在引号内,则正则表达式替换 [英] C# - Regex replace if not inside of quotes
本文介绍了C# - 如果不在引号内,则正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们看看这段代码:
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 字符串中我有一个文本,我只想替换不在引号 (\") 内的部分,但是如果我这样做了
Look that inside my Val string I have a text, I want to replace only the part which isn't inside of the quotes (\"), but if I do
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"
有人可以帮忙解决这个问题吗?我没有找到任何解释它的文档.
Can someone help to solve this problem? I didn't find any documentation explaining it.
推荐答案
您可以在引号上拆分并替换每隔一个字符串,然后将字符串放在一起:
You can split on quotation marks and do the replace on every other string, then put the strings together:
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# - 如果不在引号内,则正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文