Replacing characters got from javascript

2019-03-05 09:45发布

问题:

i'm making a program that extracts all the pictures from a flickr set. I found in the code a big String with every picture link, the problem is this:

The links have the next format:

https:\/\/c2.staticflickr.com\/4\/3925\/14562233192_3fe2b8fe1b_s.jpg

but i'm unable of removing the '\' character, despite using the "\" escape sequence.

My replacing code is the following, ret contains a lot of links separated by '\n':

ret =ret.replaceAll("\\", "");

what in the world am i forgetting?

My error stackTrace is this:

 Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal      error near index 1
 \
 ^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)

回答1:

use 4 slashes instead of 2. Like this - ret =ret.replaceAll("\\\\", ""). You need 1 for java, one for regex engine, and two to parse it literally (removing the special meaning).



回答2:

The \ is a special character in regexes, which is used to escape other special characters. Thus, to match a \, you need your regex to be \\. Since you need to escape the backslashes again (this time for the Java string), you need to call ret =ret.replaceAll("\\\\", "");.