简体   繁体   English

为什么 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);

The program isn't exiting even though the regexes should be returning true.即使正则表达式应该返回true,程序也没有退出。 What's wrong with the code?代码有什么问题?

matches returns true only if regex matches entire string .仅当正则表达式匹配整个 string 时, matches返回true In your case your regex represents only one character that is not az , AZ or .在您的情况下,您的正则表达式仅代表一个不是azAZ. . .

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 '.'

BUT if you care about performance you can use Matcher#find() method which但是如果你关心性能,你可以使用Matcher#find()方法

  1. can return true the moment it will find substring containing match for regex.可以在找到包含正则表达式匹配项的子字符串时返回true This way application will not need to check rest of the text, which saves us more time the longer remaining text is.这样应用程序就不需要检查剩余的文本,这为我们节省了更多的时间,剩余的文本越长。

  2. Will not force us to constantly build Pattern object each time String#matches(regex) is called, because we can create Pattern once and reuse it with different data.不会强迫我们在每次调用String#matches(regex)时不断构建 Pattern 对象,因为我们可以创建 Pattern 一次并使用不同的数据重用它。

Demo:演示:

Pattern p = Pattern.compile("[^a-zA-Z\\.]");

Matcher m = p.matcher("test%$@*)$(%");
if(m.find())
    System.exit(0);

//OR with Matcher inlined since we don't really need that variable
if (p.matcher("test%$@*)$(%").find())
    System.exit(0);

x.matches(y) is equivalent to x.matches(y)相当于

Pattern.compile(y).matcher(x).matches()

and requires the whole string x to match the regex y .并要求整个字符串x匹配正则表达式y If you just want to know if there is some substring of x that matches y then you need to use find() instead of matches() :如果您只想知道x某个子字符串是否与y匹配,那么您需要使用find()而不是matches()

if(Pattern.compile("[^a-zA-Z.]").matcher("test%$@*)$(%").find())
    System.exit(0);

Alternatively you could reverse the sense of the test:或者,您可以颠倒测试的意义:

if(!"test%$@*)$(%".matches("[a-zA-Z.]*"))

by providing a pattern that matches the strings that are allowed rather than the characters that aren't, and then seeing whether the test string fails to match this pattern.通过提供匹配允许的字符串而不是不匹配的字符的模式,然后查看测试字符串是否无法匹配此模式。

您始终获得 false,因为仅当模式匹配完整字符串时, matches()方法才返回 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM