java - 在逗号、句号和其他标点符号后插入空格

标签 java regex string

在 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

Working Demo

关于java - 在逗号、句号和其他标点符号后插入空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397661/

相关文章:

java - 当组件未聚焦时阻止 FocusEvents

javascript - 排序字段的正则表达式

java - String.length() 和 string.toCharArray().length 的速度/效率权衡

java - 使用spring创建多个kafka主题

java - Mockito 单元测试 stub 方法会抛出 NullPointerException

java - 从具有结束值和非结束值的字符串中查找数字

python - 正则表达式匹配列表中的项目 + 尾随 N 个数字 (Python)

c - 使用 sscanf 提取括号中嵌入的整数

在 C 中将字符串切成 2 个字符字符串的一部分,然后转换为十六进制格式(char * 到 unsigned char)

java - 如何在 Google App Engine 中动态编译 Java 类