在Java中删除标点符号前的空白

在Java中删除标点符号前的空白,java,regex,string,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}”,但无法在字符串中替换。您应该使用: 表达式的分解: \s:空白 (?=\\p{Punct})。。。后面是标

我有一根绳子

"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}”
,但无法在字符串中替换。

您应该使用:

表达式的分解:

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

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

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

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-answer更好:)

那么你想删除字符和标点符号之间的所有空白吗?我想在
\s
中添加一个
+
量词:)太好了,它起作用了。。。如果我想找到标点符号后面的空白(\\p{Punct}=?)或其他什么,请你解释一下,然后我可以多做一些吗?
String text = "This is a big sentence . ! ? ! but I have to remove the space .";
String replaced = text.replaceAll("\\s+(\\p{Punct})", "$1")