How to remove all commas that are inside quotes (") with C# and regex

与世无争的帅哥 提交于 2019-12-19 10:05:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!