如何删除 "(双引号)和 "(双引号)之间的 ,(逗号)。就像有 "a","b","c","d,d","e","f"
然后从这里开始,在 "和 "之间有一个逗号应该被删除,删除该逗号后,在 C# 中的正则表达式的帮助下,它应该是 "a","b","c","dd","e","f"
?
编辑:我忘记指定引号之间可能有双逗号,例如 "a","b","c","d,d,d","e ","f"
因为正则表达式不起作用。引号之间可以有任意数量的逗号。
并且可以有像 a,b,c,"d,d",e,f
这样的字符串然后应该有像 a,b,c,dd,e, f
如果字符串像 a,b,c,"d,d,d",e,f
那么结果应该像 a,b,c,ddd,e ,f
.
最佳答案
假设输入与您的示例一样简单(即,不是完整的 CSV 数据),应该这样做:
string input = @"a,b,c,""d,d,d"",e,f,""g,g"",h";
Console.WriteLine(input);
string result = Regex.Replace(input,
@",(?=[^""]*""(?:[^""]*""[^""]*"")*[^""]*$)",
String.Empty);
Console.WriteLine(result);
输出:
a,b,c,"d,d,d",e,f,"g,g",h a,b,c,"ddd",e,f,"gg",h
The regex matches any comma that is followed by an odd number of quotation marks.
EDIT: If fields are quoted with apostrophes ('
) instead of quotation marks ("
), the technique is exactly the same--except you don't have to escape the quotes:
string input = @"a,b,c,'d,d,d',e,f,'g,g',h";
Console.WriteLine(input);
string result = Regex.Replace(input,
@",(?=[^']*'(?:[^']*'[^']*')*[^']*$)",
String.Empty);
Console.WriteLine(result);
如果某些字段用撇号引用而其他字段用引号引用,则需要采用不同的方法。
编辑:可能应该在之前的编辑中提到这一点,但您可以将这两个正则表达式组合成一个正则表达式,该正则表达式将处理或者撇号或引号(但不两者):
@",(?=[^']*'(?:[^']*'[^']*')*[^']*$|[^""]*""(?:[^""]*""[^""]*"")*[^""]*$)"
实际上,它将处理像'a,a',"b,b"
这样的简单字符串。问题是没有什么可以阻止您在另一种类型的引用字段中使用其中一个引号字符,例如 '9"Nails'
(sic) 或 "Kelly's Heroes “
。这让我们进入了成熟的 CSV 领域(如果不是超越的话),我们已经确定我们不会去那里。:D
关于c# - Regex-如何删除 "and "之间的逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5202005/