1

我有一个字符串,

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

4 回答 4

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

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

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

于 2012-08-08T14:15:24.143 回答
4
sample = sample.replaceAll(" ,", ",").replaceAll(" )", ")");

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

sample = sample.replaceAll("\\s+,", ",").replaceAll("\\s+\\)", ")");
于 2012-08-08T14:15:52.690 回答
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(" ,", ",");
于 2012-08-08T14:18:57.453 回答
0

此正则表达式应删除前后的空格 -

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

于 2021-07-05T15:26:13.853 回答