Java String.replace/replaceAll not working

2020-01-29 20:55发布

So, I'm trying to parse a String input in Java that contains (opening) square brackets. I have str.replace("\\[", ""), but this does absolutely nothing. I've tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it's been that way for over a year and hasn't caused me any issues like this before.

Any idea what I might be doing wrong here?

3条回答
干净又极端
2楼-- · 2020-01-29 21:10

Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:

str = str.replaceAll("\\[", "");

For the normal replace method, you don't need to escape the bracket:

str = str.replace("[", "");
查看更多
Viruses.
3楼-- · 2020-01-29 21:20

As always, the problem is not that "xxx doesn't work", it is that you don't know how to use it.

First things first:

  • a String is immutable; if you read the javadoc of .replace() and .replaceAll(), you will see that both specify that a new String instance is returned;
  • replace() accepts a string literal as its first argument, not a regex literal.

Which means that you probably meant to do:

str = str.replace("[", "");

If you only ever do:

str.replace("[", "");

then the new instance will be created but you ignore it...


In addition, and this is a common trap with String (the other being that .matches() is misnamed), in spite of their respective names, .replace() does replace all occurrences of its first argument with its second argument; the only difference is that .replaceAll() accepts a regex as a first argument, and a "regex aware" expression as its second argument; for more details, see the javadoc of Matcher's .replaceAll().

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-29 21:25
public String replaceAll(String regex, String replacement)

As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like "(", ")" etc (with "\") if these exists in your replacement text which is to be replaced out of the string. For example :

String oldString = "This is (stringTobeReplaced) with brackets.";

String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", "");
System.out.println(newString); // will output "This is  with brackets."

Another way of doing this is to use Pattern.quote("str") :

    String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");

This will consider the string as literal to be replaced.

查看更多
登录 后发表回答