当前位置: 动力学知识库 > 问答 > 编程问答 >

java - pattern method matches returns false

问题描述:

I have

String b = "aasf/sdf/dfd/*";

Pattern.matches("[^ ]", b);

I keep getting returned false in Patter.matches();

Since it matches regex, all characters beside space character, shouldn't it return true?

网友答案:

Pattern.matches would try to match the pattern exactly..

So it would return true only if you have a single non space character as input.

Its like using \A[^ ]\z

where \A is the beginning of input and \z is end of input..


If you want to check for strings that doesn't contain space you can use

input.matches("[^ ]*");
网友答案:

No, coz you try to match whole string to NON-SPACE character.

String b = "aasf/sdf/dfd/*";
Pattern.matches("[^ ]*", b);

This one will return true

网友答案:

As anirudh suggested, Pattern matchers are used differently (see the other answers for examples), I believe that what you were trying to do is the following:

    String b = "aasf/sdf/dfd/*";
    System.out.println("b.matches(\"[^ ]\") = " + b.matches("[^ ]"));

OUTPUT

b.matches("[^ ]") = false
网友答案:

Pattern.matches() returns true only if the entire string matches the regex. What you want to do is to see if the pattern occurs anywhere in the String. You need to use Matcher.find() for that.

e.g,

    String testStr = "aasf/sdf/dfd/*";
    Pattern patt = Pattern.compile("[^ ]");
    Matcher m = patt.matcher(testStr);
    while (m.find()) {
        System.out.println(m.group(0));
    }

This will print all matches. If you just need to know if a pattern is found, just check if m.find() is true.

分享给朋友:
您可能感兴趣的文章:
随机阅读: