在 Java 中,修复某些标点符号后缺少空格的最佳方法是什么,例如:
, . ; : ? !
例如:
String example = "This is!just an:example,of a string,that needs?to be fixed.by inserting:a whitespace;after punctuation marks.";
输出应该是:
"This is! just an: example, of a string, that needs? to be fixed. by inserting: a whitespace; after punctuation marks."
很明显,这是行不通的:
example = example.replaceAll("[,.!?;:]", " ");
所以我正在寻找解决方案,等待您的帮助。 谢谢!!
最佳答案
您可以使用 Positive Lookbehind and Negative Lookahead 的组合.
example = example.replaceAll("(?<=[,.!?;:])(?!$)", " ");
解释:
Positive Lookbehind 在任何选择的标点符号之后的位置断言。 Negative Lookahead 的使用表示,在这个位置(字符串的结尾),以下内容无法匹配。
(?<= # look behind to see if there is:
[,.!?;:] # any character of: ',', '.', '!', '?', ';', ':'
) # end of look-behind
(?! # look ahead to see if there is not:
$ # before an optional \n, and the end of the string
) # end of look-behind
关于java - 在逗号、句号和其他标点符号后插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397661/