如何在字符串中的$后删除空格?

时间:2016-02-16 17:53:38

标签: java regex

我有一个输入,在$和值之间有一个空格,我想删除空格。这段代码:

System.out.println("This costs $ 5 even.".replaceAll("\\$ ", "$"));

应打印出来:

This costs $5 even.

但它引发了一个例外:

Illegal group reference: group index is missing
java.lang.IllegalArgumentException
    at java.util.regex.Matcher.appendReplacement(Matcher.java:819)
    at java.util.regex.Matcher.replaceAll(Matcher.java:955)
    at java.lang.String.replaceAll(String.java:2223)
    at DollarTest.test(DollarTest.java:18)

我错过了什么?

4 个答案:

答案 0 :(得分:12)

只需使用replace()

System.out.println("This costs $ 5 even.".replace("$ ", "$"));

答案 1 :(得分:6)

问题是在正则表达式替换字符串中,$是特殊的。它应该用于指代正则表达式本身的捕获组。

你需要逃脱它:

.replaceAll("\\$ ", "\\$")

但是as @pp_ mentions,你最好在这里使用普通的.replace()

答案 2 :(得分:2)

另一种选择 - 在空格周围对$和值进行分组,然后在替换中将它们连接起来。

String s = "This costs $ 5 even. That costs $ 6 even. This is a $ sign.";
System.out.println(s.replaceAll("(\\$)\\s(\\d+)", "$1$2"));

输出

This costs $5 even. That costs $6 even. This is a $ sign.

它还指出了其他答案中的缺陷

String s = "This costs $ 5 even. That costs $ 6 even. This is a $ sign.";
System.out.println(s.replaceAll("\\$ ", "\\$"));

输出"$sign"

This costs $5 even. That costs $6 even. This is a $sign.

答案 3 :(得分:1)

我建议您使用以下正则表达式删除$和下一个数字之间的任意数量的空格。

try {
    String data = "This costs $          7 even";
    String resultString = data.replaceAll("(?is)(?<=\\$)\\s*(?=\\d+)", "");
    System.out.println(resultString);

} catch (PatternSyntaxException ex) {

}
  

输入:

This costs $ 5 even
This costs $6 even
This costs $          7 even
This costs $          77 even
This costs $          7.2 even
This costs $          0.21 even
It's cost is between $   5.2 and $   8.3
You don't have to pay top $ for this.
  

输出:

This costs $5 even
This costs $6 even
This costs $7 even
This costs $77 even
This costs $7.2 even
This costs $0.21 even
It's cost is between $5.2 and $8.3
You don't have to pay top $ for this.