简体   繁体   English

如何使用C#和正则表达式删除引号(“)内的所有逗号

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

How to build a regex to remove all commas that are inside quotes(") using C# and then substitute them by @? 如何使用C#构建正则表达式以删除引号(“)内的所有逗号,然后将其替换为@?

Example : 范例

Initial string like this = (value 1,value 2,"value3,value4,value5",value 6) 像这样的初始字符串= (value 1,value 2,"value3,value4,value5",value 6)

Expected string like this = (value 1,value 2,"value3@value4@value5", value 6) 期望的字符串,例如= (value 1,value 2,"value3@value4@value5", value 6)

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(',','@'));
string input = "= (value 1,value 2,\"value3,value4,value5\",value 6)";
string pattern = "(?<=\".*),(?=.*\")";
string result = Regex.Replace(input, pattern, "@");

Regex pattern referred below would work to identify data within double quotes even in multiple level Regex pattern: ([\\"].*[\\"]) 下面提到的Regex模式即使在多层Regex模式中也可以识别双引号中的数据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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM