简体   繁体   English

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

[英]How do I remove the space after a $ in a String?

I have an input with a space between the $ and the value, and I'd like to remove the space. 我有一个输入,$和值之间有一个空格,我想删除空格。 This code: 这段代码:

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

should print out: 应该打印出来:

This costs $5 even.

but it throws an exception: 但它抛出一个异常:

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)

What am I missing? 我想念什么?

只需使用replace()

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

The problem is that in a regex replacement string, the $ is special. 问题在于,在正则表达式替换字符串中, $是特殊的。 It is supposed to be used to refer to a capturing group of the regex itself. 应该使用它来指代正则表达式本身的捕获组。

You need to escape it: 您需要对其进行转义:

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

But as @pp_ mentions , you are better off using a plain .replace() here. 但是正如@pp_所提到的 ,最好在这里使用普通的.replace()

Another alternative - group the $ and the value, around the space, then concat them in the replacement. 另一种选择-将$和值分组在空格周围,然后在替换中合并它们。

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

Output 输出量

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

It also points out a flaw in the other answers 它还指出了其他答案中的缺陷

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

Outputs "$sign" . 输出"$sign"

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

I'd suggest you to use following regex to remove any number of spaces between $ and next number. 我建议您使用以下正则表达式删除$和下一个数字之间的任意数量的空格。

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

} catch (PatternSyntaxException ex) {

}

Input: 输入:

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.

Output: 输出:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM