简体   繁体   English

替换$中的字符串

[英]Replace $ sign in String

I used the following line to remove all $ signs and spaces in a given data "DATA": 我使用以下行删除给定数据“DATA”中的所有$符号和空格:

String temp_data = DATA.replaceAll("$", "").replaceAll(" ", "");

But it won't remove the $ signs, only the spaces. 但它不会删除$符号,只删除空格。 Does someone have any idea why? 有人知道为什么吗?

Thanks, Binyamin 谢谢,Binyamin

The first parameter replaceAll takes is a regex, and the regex engine treats $ as a special character that stands for the end of the line. 第一个参数replaceAll采用的是正则表达式,正则表达式引擎将$视为代表行尾的特殊字符。 Escape it with \\ like this: 用\\来逃避它:像这样:

String temp_data = DATA.replaceAll("\\$", "").replaceAll(" ", "");

Here's an example using replaceAll and replace: 这是使用replaceAll和replace的示例:

import junit.framework.TestCase;

public class ReplaceAllTest extends TestCase {

    private String s = "asdf$zxcv";

    public void testReplaceAll() {
        String newString = s.replaceAll("\\$", "X");
        System.out.println(newString);
        assertEquals("asdfXzxcv", newString);
    }

    public void testReplace() {
        String newString =s.replace("$", "");
        System.out.println(newString);
        assertEquals("asdfzxcv", newString);
    }
}

replaceAll takes a regular expression - and "$" has special meaning in regular expressions. replaceAll采用正则表达式 - “$”在正则表达式中具有特殊含义。

Try just replace instead: 请尝试replace

String temp_data = DATA.replace("$", "").replace(" ", "");

String.replaceAll uses a regular expression for matching the characters that should be replaced. String.replaceAll使用正则表达式来匹配应替换的字符。 In regular expressions however, $ is a special symbol signalizing the end of the string, so it is not recognized as the character itself. 但是在正则表达式中, $是表示字符串结尾的特殊符号,因此不会将其识别为字符本身。

You can either escape the $ symbol, or just use the String.replace method which works on a plain string: 您可以转义$符号,或者只使用适用于纯字符串的String.replace方法:

String temp_data = DATA.replace( "$", "" ).replace( " ", "" );

// or
String temp_data = DATA.replaceAll( "\\$", "" ).replaceAll( " ", "" );

// or even
String temp_data = DATA.replaceAll( "\\$| ", "" );

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

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