之前和之后的特殊字符

问题描述:

我有一个字符串删除空间,之前和之后的特殊字符

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 

任何人都可以请告诉我如何做到这一点?

+0

用“)”替换所有“)”,重复应用,直到没有任何东西被替换。 – 2012-08-08 14:15:30

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

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

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

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

如果你想),之前移除任何数量的空格,您可以使用正则表达式:

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

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(" ,", ",");