public static void main(String[] args) {
String s = "a";
s = s.replaceAll(".", "\\");
}
above procedure given as follows:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
what is the reason ? Thank you !
------ Solution ---------------------------------------- ----
replaceAll parameter is the regex, regular expressions , the first will escape , so the error .
the program can be changed to the following
public static void main(String[] args) {
String s = "a";
s = s.replaceAll(".", "\\\\");
}
------ Solution ------------------------------------- -------
java replaceAll () method to use four backslash represents a backslash
example str1 = "aa \ bbb"; str2 = "aa'bbb";
To replace str1 = "aa \ \ bbb"; str2 = "aa \ 'bbb";
must replace this :
str1 = str1.replaceAll ("\ \ \ \", " \ \ \ \ \ \ \ \ " ) ;
str2 = str2.replaceAll ("'", "\ \ \ \ ' " ) ;
for the following reasons :
String of replaceAll () method is actually using regular expressions to match the rule ,
\ \ \ \, java resolves to \ \ to regular expressions , regular expressions, and then after a conversion , the \ \ converted into \
which is to use regular java to represent a \ must be written 4 \
If you said \ \ , then write 8 \
So if written : str1 = str1.replaceAll ("\ \", "\ \ \ \");
error will be reported regular expressions .
------ Solution ---------------------------------------- ----
It seems that the amount of my explanation is not in place , +1
------ For reference only --------------- ------------------------
shortly before seen, specific links in this http://bbs.csdn.net/topics/200023433
------ For reference only -------------------------------------- -
---- - For reference only ---------------------------------------
regex in \ \ represents \
The java language \ \ represents the character \ , and therefore represents two \ \ must use \ \ \ \
没有评论:
发表评论