正则表达式查找和转义用双引号括起来的双引号

时间:2013-09-25 18:36:31

标签: c# regex

假设我想要转义嵌套在双引号内的所有双引号(图片为CSV或其他内容):

"Jim", "Smythe", "Favorite Quote: "This is my favorite quote.""

我想隔离围绕This is my favorite quote.的内部引号,然后用\转义它们。但是我在写一个正则表达式以匹配内部引号时遇到了麻烦。所以,我想要的结果是:

"Jim", "Smythe", "Favorite Quote: "This is my favorite quote.""
                                  ^^                        ^^
                 Start Match Here ||                        || End Match Here
                Start Capture Here |       End Capture Here |

Match:   "This is my favorite quote."
Capture:  This is my favorite quote.

然后我可以轻松地使用模式\"$1\"来转义引号以获得最终结果:

"Jim", "Smythe", "Favorite Quote: \"This is my favorite quote.\""

2 个答案:

答案 0 :(得分:2)

我建议:

(?<!^|, )"(?=(?:(?<!"),|[^,])*"(?:,|$))

替换为\\$0

regex101 demo

答案 1 :(得分:1)

这对我有用:

string input = "\"Jim\" , \"Smythe\", \"Favorite Quote: \"This is my favorite quote.\"\"";
var output = Regex.Match(input,"\"(?!\\s*,\\s*\")((?<!(,|^)\\s*\"\\w*?)[^\"]+)\"").Groups[1].Value;
//output = This is my favorite quote.

var replacedOutput = Regex.Replace(input, "\"(?!\\s*,\\s*\")((?<!(,|^)\\s*\"\\w*?)[^\"]+)\"", "\\\"$1\\\"");