如何用空格替换所有带空格的逗号只能在字符串中?

时间:2017-12-20 05:48:04

标签: java regex string

我拥有的是:

"atul ,   singh Java   ,  computer science and engineering     ,    Data structures &   algorithms" 

我想要的是:

"atul,singh Java,computer science and engineering,Data structures &   algorithms"

任何人都可以告诉我该怎么做?

3 个答案:

答案 0 :(得分:3)

您可以使用此正则表达式:

\s*,\s*

在java中:

your_string= your_string.replaceAll("\\s*,\\s*", ",");

<强>解释

  • \s* - 匹配一串全部&#34;空格&#34; (空格,标签,换行符等)
  • , - 匹配角色&#34;,&#34;

答案 1 :(得分:2)

接受你的意见。

使用.split("\\s+,\\s+")取出逗号和周围的whites间距。如果逗号两边都没有空格,请将+&#34;替换为*

将该字符串数组与逗号连接起来,没有空格

答案 2 :(得分:0)

试试这个

String a= " atul ,  singh Java , computer science and engineering , Data structures & algorithms ";
String b[]= a.split(",");
String c = "";
for(int i=0;i<b.length;i++){
  c+=b[i].trim()+",";
}
System.out.println(c.substring(0,c.length()-1));
}
相关问题