【发布时间】:2015-10-05 17:12:25
【问题描述】:
我需要在字符串中的所有标点符号之间添加空格。
\\ "Hello: World." -> "Hello : World ."
\\ "It's 9:00?" -> "It ' s 9 : 00 ?"
\\ "1.B,3.D!" -> "1 . B , 3 . D !"
我认为正则表达式是要走的路,匹配所有非标点符号[a-ZA-Z\\d]+,在之前和/或之后添加一个空格,然后提取匹配所有标点符号[^a-ZA-Z\\d]+ 的余数。
但我不知道如何(递归?)调用这个正则表达式。看第一个例子,正则表达式只会匹配"Hello"。我正在考虑通过不断删除和附加匹配的正则表达式的第一个实例来构建一个新字符串,而原始字符串不为空。
private String addSpacesBeforePunctuation(String s) {
StringBuilder builder = new StringBuilder();
final String nonpunctuation = "[a-zA-Z\\d]+";
final String punctuation = "[^a-zA-Z\\d]+";
String found;
while (!s.isEmpty()) {
// regex stuff goes here
found = ???; // found group from respective regex goes here
builder.append(found);
builder.append(" ");
s = s.replaceFirst(found, "");
}
return builder.toString().trim();
}
但是,这感觉不是正确的方法……我想我把事情复杂化了……
【问题讨论】: