0

假设我想转义嵌套在双引号内的所有双引号(图片 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.\""
4

2 回答 2

2

我建议:

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

用。。。来代替\\$0

正则表达式101演示

于 2013-09-25T19:07:44.487 回答
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\\\"");
于 2013-09-25T19:04:56.537 回答