當我做String.replaceFirst錯誤? Java的
String s = "2r2";
System.out.println(s.replaceFirst("2r2","4"));
它的工作原理,打印4,但是當我做
String s = "2^2";
System.out.println(s.replaceFirst("2^2","4"));
它不工作(它打印2^2),爲什麼呢?我該怎麼辦?
當我做String.replaceFirst錯誤? Java的
String s = "2r2";
System.out.println(s.replaceFirst("2r2","4"));
它的工作原理,打印4,但是當我做
String s = "2^2";
System.out.println(s.replaceFirst("2^2","4"));
它不工作(它打印2^2),爲什麼呢?我該怎麼辦?
replaceFirst
正在使用正則表達式語法,其中^
有特殊含義(它表示字符串或行的開始,取決於使用的修飾符)。
您需要轉義^
,比如"2\\^2"
,或者爲了讓您的生活更簡單,請使用Pattern.quote("2^2")
爲您做到這一點。
所以,你的代碼應該更像:
String s = "2^2";
System.out.println(s.replaceFirst(Pattern.quote("2^2"),"4"));
在正則表達式中,^
字符有着特殊的含義。它匹配一行的開始。
改爲使用s.replaceFirst("2\\^2","4")
- 反斜槓意味着將^
視爲正常字符,而不是將其賦予其特殊含義。