从键盘读取时,希腊字符串与正则表达式不匹配

ath*_*spk 11 java regex

public static void main(String[] args) throws IOException {
   String str1 = "??123456";
   System.out.println(str1+"-"+str1.matches("^\\p{InGreek}{2}\\d{6}")); //??123456-true

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String str2 = br.readLine(); //??123456 same as str1.
   System.out.println(str2+"-"+str2.matches("^\\p{InGreek}{2}\\d{6}")); //?”??123456-false

   System.out.println(str1.equals(str2)); //false
}
Run Code Online (Sandbox Code Playgroud)

从键盘读取时,相同的String与正则表达式不匹配.
是什么导致了这个问题,我们如何解决这个问题呢?
提前致谢.

编辑:我使用System.console()进行输入和输出.

public static void main(String[] args) throws IOException {
        PrintWriter pr = System.console().writer();

        String str1 = "??123456";
        pr.println(str1+"-"+str1.matches("^\\p{InGreek}{2}\\d{6}")+"-"+str1.length());

        String str2 = System.console().readLine();
        pr.println(str2+"-"+str2.matches("^\\p{InGreek}{2}\\d{6}")+"-"+str2.length());

        pr.println("str1.equals(str2)="+str1.equals(str2));
}
Run Code Online (Sandbox Code Playgroud)

输出:

ΔΞ123456真-8-
ΔΞ123456
ΔΞ123456真-8
str1.equals(STR2)=真

McD*_*ell 9

有很多地方可以在这​​里进行转码错误.

  1. 确保正确编译您的类(不太可能是IDE中的问题):
    • 确保编译器使用与编辑器相同的编码(即,如果保存为UTF-8,请将编译器设置为使用该编码)
    • 或者切换到转义为大多数编码都是超集的ASCII子集(即将字符串文字更改为"\u0394\u039e123456")
  2. 确保使用正确的编码读取输入:

请注意,System.console()在IDE 中返回null,但您可以对此进行操作.


axt*_*avt 8

如果您使用Windows,可能是因为控制台字符编码("OEM代码页")与系统编码("ANSI代码页")不同.

InputStreamReader 如果没有显式编码参数,则假定输入数据为系统默认编码,因此从控制台读取的字符将被错误地解码.

为了在Windows控制台中正确读取非us-ascii字符,您需要在构造时显式指定控制台编码InputStreamReader(可以通过mode con cp在命令行中执行找到所需的代码页编号):

BufferedReader br = new BufferedReader(
    new InputStreamReader(System.in, "CP737")); 
Run Code Online (Sandbox Code Playgroud)

同样的问题适用于输出,您需要PrintWriter使用适当的编码构造:

PrintWriter out = new PrintWrtier(new OutputStreamWriter(System.out, "CP737"));
Run Code Online (Sandbox Code Playgroud)

请注意,从Java 1.6开始,您可以通过使用Console从中获取的对象来避免这些变通方法System.console().它提供ReaderWriter与正确配置编码以及一些实用的方法.

但是,重定向流时System.console()返回null(例如,从IDE运行时).可以在McDowell的答案中找到解决此问题的方法.

也可以看看: