Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-删除引号字符串外逗号周围的空格?_Java_Regex_String - Fatal编程技术网

Java-删除引号字符串外逗号周围的空格?

Java-删除引号字符串外逗号周围的空格?,java,regex,string,Java,Regex,String,我有一个字符串,如下所示: String s = "A, Category, \"Agriculture, forestry and fishing\","; 我想删除逗号周围的空格(在引号外)。因此,我的字符串应该如下所示: A,Category,"Agriculture, forestry and fishing", 我尝试了以下方法: String s = s.replaceAll("[,]\\s+", ","); 但产出是: A,Category,"Agriculture,f

我有一个字符串,如下所示:

String s = "A,  Category,   \"Agriculture, forestry and fishing\",";
我想删除逗号周围的空格(在引号外)。因此,我的字符串应该如下所示:

A,Category,"Agriculture, forestry and fishing",
我尝试了以下方法:

String s = s.replaceAll("[,]\\s+", ",");
但产出是:

A,Category,"Agriculture,forestry and fishing",
我应该在正则表达式中做哪些更改以避免引号内逗号的更改?

您可以使用以下方法:

String str = "A,  Category,   \"Agriculture, forestry and fishing\",";
String result = str.replaceAll(" (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", "");
//------------------------------^--------------------------------------
System.out.println(result);
String result = str.replaceAll("(\\s*,\\s*)(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", ",");
这将打印:

A,Category,"Agriculture, forestry and fishing",
//----------------------^---------------------
引号内的空间不是变化,只是引号外的空间


这是一个,这是一个


编辑

此部分来自@Exception\u al,因此他建议使用此部分:

String str = "A,  Category,   \"Agriculture, forestry and fishing\",";
String result = str.replaceAll(" (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", "");
//------------------------------^--------------------------------------
System.out.println(result);
String result = str.replaceAll("(\\s*,\\s*)(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", ",");
如果要替换逗号
和单词之间的所有空格,此解决方案非常好


您可以检查它在类似CSV(逗号分隔值)数据的

中的工作方式,因此使用CSV解析器解析数据并重新格式化。只需将其更改为:
String result=str.replaceAll((\s*,\s*)(?=(?:[^\“]*\”[^\“]*\”[^\“]*\”[^\“]*$”,“,”)
这将占用多个空格,并将其删除…而且不会触及单词之间的空格。哈哈,所以你取消了对@Exception的追加投票。好吧,你的答案已经全部(几乎)完成了…想法是回答OPs查询…我想建议编辑,但Q显然已满,所以我发表了评论!!!你做了大部分工作…你也给出了答案。好的,你想让我在我的答案中添加你的解决方案@Exception\u al?谢谢@Exception\u al我已经将其添加到我的问题中了,我在那里提到了你的名字,希望这能让你开心y;)