问题
How to build a regex to remove all commas that are inside quotes(") using C# and then substitute them by @?
Example:
Initial string like this = (value 1,value 2,"value3,value4,value5",value 6)
Expected string like this = (value 1,value 2,"value3@value4@value5", value 6)
回答1:
You can use
string input = "(value 1,value 2,\"value3,value4,value5\",value 6)";
var regex = new Regex("\\\"(.*?)\\\"");
var output = regex.Replace(input, m => m.Value.Replace(',','@'));
回答2:
string input = "= (value 1,value 2,\"value3,value4,value5\",value 6)";
string pattern = "(?<=\".*),(?=.*\")";
string result = Regex.Replace(input, pattern, "@");
回答3:
Regex pattern referred below would work to identify data within double quotes even in multiple level
Regex pattern: ([\"].*[\"])
List<string> input = new List<string>();
input.Add("= (value 1,value 2,\"value3,value4,value5\",value 6)");
input.Add("\"(value 1,value 2,\"value 3, value 4\",value 5,value 6)\"");
var regex = new Regex("([\"].*[\"])");
List<string> output = input.Select(data => regex.Replace(data, m=> m.Value.Replace(',','@'))).ToList();
foreach(string dat in output)
Console.WriteLine(dat);
来源:https://stackoverflow.com/questions/39807592/how-to-remove-all-commas-that-are-inside-quotes-with-c-sharp-and-regex