为什么String.matches在Java中返回false? [英] Why is String.matches returning false in Java?
问题描述
if("test%$@*)$(%".matches("[^a-zA-Z\\.]"))
System.exit(0);
if("te/st.txt".matches("[^a-zA-Z\\.]"))
System.exit(0);
即使正则表达式应该返回true,程序也不会退出。代码出了什么问题?
The program isn't exiting even though the regexes should be returning true. What's wrong with the code?
推荐答案
匹配
返回 true
仅当整个字符串与正则表达式匹配时。在您的情况下,您的正则表达式仅代表一个字符,该字符不是 az
, AZ
或
。
matches
returns true
only if entire string matches regex. In your case your regex represents only one character that is not a-z
, A-Z
or .
.
我怀疑你想检查字符串是否包含你在regex中描述的这些特殊字符之一。在这种情况下,使用。*
围绕正则表达式,让正则表达式匹配整个字符串。哦,你不必逃避。
里面的字符类 [。]
。
I suspect that you want to check if string contains one of these special characters which you described in regex. In that case surround your regex with .*
to let regex match entire string. Oh, and you don't have to escape .
inside character class [.]
.
if ("test%$@*)$(%".matches(".*[^a-zA-Z.].*")) {
//string contains character that is not in rage a-z, A-Z, or '.'
这篇关于为什么String.matches在Java中返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!