在Java中标点符号之前删除空格

时间:2011-08-03 14:40:36

标签: java regex string

我有一个字符串

"This is a big sentence .  !  ?  !  but I have to remove the space ."   

在这句话中,我想删除标点符号之前的所有空格,并且应该成为

"This is a big sentence.!?!  but I have to remove the space."   

我正在尝试使用"\p{Punct}"但无法替换为字符串。

3 个答案:

答案 0 :(得分:10)

您应该使用positive lookahead

newStr = str.replaceAll("\\s+(?=\\p{Punct})", "")

ideone.com demo for your particular string

分解表达式:

  • \s:空格......
  • (?=\\p{Punct}) ...之后是标点符号。

答案 1 :(得分:1)

尝试使用此正则表达式查找标点符号前面的所有空格:\s+(?=\p{Punct})(Java字符串:"\\s+(?=\\p{Punct})"

答案 2 :(得分:0)

您可以使用组并在替换字符串中引用它:

String text = "This is a big sentence . ! ? ! but I have to remove the space .";
String replaced = text.replaceAll("\\s+(\\p{Punct})", "$1")

在这里,我们使用(\\p{Punct})捕获组中的标点符号,并将所有匹配的字符串替换为组(名为$1)。

无论如何,我的答案仅仅是好奇心:我认为@aioobe答案更好:)

相关问题