开发者

Replace $ sign in String

I used the following line to remove all $ signs and spaces in a given 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, Binya开发者_如何学Pythonmin


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. Escape it with \ like this:

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

Here's an example using replaceAll and 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.

Try just replace instead:

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


String.replaceAll uses a regular expression for matching the characters that should be replaced. 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 temp_data = DATA.replace( "$", "" ).replace( " ", "" );

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜