Java正則轉義星號* 加號+ 反斜槓\
阿新 • • 發佈:2019-01-26
問題引入:
這是我在使用Java正則表示式時,需要將已有的正則表示式和使用者輸入的字串進行拼接,然後將新的字串當作一個正則表示式來使用,這時,問題來了,如果使用者輸入連續的星號* 或者連續的加號+ 或者是反斜槓\ 就會導致String.matches()則會丟擲異常PatternSyntaxException
為了解決這個問題,就需要對使用者輸入的字元進行轉義.
程式碼如下:
public static void main(String[] args) {
//字串a\bc\de\fg中有3個反斜槓'\',將反斜槓進行轉移為雙反斜槓\\
String str1 = "a\\bc\\de\\fg" ;
System.out.println(str1);
String result = str1.replaceAll("\\\\", "\\\\\\\\");
System.out.println(result);
//方法二,用replace()
result = str1.replace("\\", "\\\\");
System.out.println("2:" + result);
//字串a****bcd中有4個星號,轉義星號*
String str2 = "a****bcd" ;
System.out.println(str2);
String result2 = str2.replaceAll("\\*", "\\\\*");
System.out.println(result2);
//字串a++++bcd中有4個星號,轉義加號+
String str3 = "a++++bcd";
System.out.println(str3);
String result3 = str3.replaceAll("\\+", "\\\\+");
System.out.println(result3);
}