在逗号,句点和其他标点符号后插入空格

Mar*_*iaH 3 java regex string

在Java中,在一些标点符号之后修复丢失的空格的最佳方法是:

, . ; : ? !
Run Code Online (Sandbox Code Playgroud)

例如:

String example = "This is!just an:example,of a string,that needs?to be fixed.by inserting:a whitespace;after punctuation marks.";
Run Code Online (Sandbox Code Playgroud)

输出应该是:

"This is! just an: example, of a string, that needs? to be fixed. by inserting: a whitespace; after punctuation marks."
Run Code Online (Sandbox Code Playgroud)

很明显,这不起作用:

example = example.replaceAll("[,.!?;:]", " ");
Run Code Online (Sandbox Code Playgroud)

所以我正在寻找一个等待你帮助的解决方案.谢谢!!

Fed*_*zza 6

您必须添加$0到替换表达式中,您可以使用:

example = example.replaceAll("[,.!?;:]", "$0 ");
Run Code Online (Sandbox Code Playgroud)

它将用该内容和一个空格替换您匹配的正则表达式。

顺便说一句,如果你想确保你没有多个空格,你可以这样做:

example = example.replaceAll("[,.!?;:]", "$0 ").replaceAll("\\s+", " "); 
Run Code Online (Sandbox Code Playgroud)

将转换:

这只是一个:字符串的例子,需要修复。通过插入:一个空格;在标点符号之后。

到:

这是!只是一个:例如,一个字符串,需要吗?等待修复。通过插入:一个空格;标点符号后。


hwn*_*wnd 6

您可以使用Positive LookbehindNegative Lookahead的组合.

example = example.replaceAll("(?<=[,.!?;:])(?!$)", " ");
Run Code Online (Sandbox Code Playgroud)

说明:

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
Run Code Online (Sandbox Code Playgroud)

工作演示