删除特殊字符前后的空格

时间:2012-08-08 14:13:28

标签: java string

我有一个字符串,

String sample = "He won the International Rating Chess Tournament (IRCT ) which concluded on Dec. 22 at the Blue Sky Hotel , Canada";

我想在字符')'和','之前删除空格(,如果有的话)。所以最终输出应该是,

He won the International Rating Chess Tournament (IRCT) which concluded on Dec. 22 at the Blue Sky Hotel, Canada

有人可以告诉我怎么做吗?

4 个答案:

答案 0 :(得分:6)

sample.replaceAll("\\s+(?=[),])", "");

即。删除紧跟\s+以下任何字符(?=...)的所有空格[),]。双反斜杠用于逃逸。有关正则表达式的更多信息可以在这里看到:

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

答案 1 :(得分:3)

sample = sample.replaceAll(" ,", ",").replaceAll(" )", ")");

如果要在),之前删除任意数量的空格,可以使用正则表达式:

sample = sample.replaceAll("\\s+,", ",").replaceAll("\\s+\\)", ")");

答案 2 :(得分:1)

    String sample = "He won the International Rating Chess Tournament (IRCT ) which concluded on Dec. 22 at the Blue Sky Hotel , Canada";
    sample=sample.replace(" )", ")");
    sample=sample.replace(" ,", ",");

答案 3 :(得分:0)

这个正则表达式应该删除前后的空格 -

\s+(?=[-])|(?<=-)\s*