Java语法相关,什么情况下需要多打一个"\"?
import java.util.Scanner;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str;
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
int index = str.indexOf('[');
int lastIndex = str.lastIndexOf(']');
str = str.substring(index + 1, lastIndex);
String s = "1";
System.out.println("str:" + str);
if (Pattern.matches(str, s))
System.out.println("str与s匹配成功!");
else System.out.println("str与s匹配失败!");
String str1 = "\\d";
System.out.println("str1:" + str1);
if (Pattern.matches(str1, s))
System.out.println("str1与s匹配成功!");
else System.out.println("str1与s匹配成功!");
System.out.println(str1.equals(str));
}
}
输入为 [\d] 时
输入为 [\\d]时
从外部读入时无需考虑转义,程序内部定义字符串时需要考虑转义。