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)=真
如果您使用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().它提供Reader和Writer与正确配置编码以及一些实用的方法.
但是,重定向流时System.console()返回null(例如,从IDE运行时).可以在McDowell的答案中找到解决此问题的方法.
也可以看看:
| 归档时间: |
|
| 查看次数: |
1619 次 |
| 最近记录: |