简体   繁体   中英

Why doesn't Pattern.matches(“[a*mn]”,“aaaa”) return true? What should be proper code to get the desired output?

I want to create a pattern where the desired string should either be multiples of a including null ie a*, or it should be one single m or single n. But the following code doesn't give the desired output.

class Solution {
            public static void main(String args[]) {
                System.out.println(Pattern.matches("[a*mn]", "aaaa"));
        }
}

* within a character class ( [] ) is just a * , not a quantifier.

I want to create a pattern where the desired string should either be multiples of a including null ie a*, or it should be one single m or single n.

You'll need an alternation ( | ) for that: a*|[mn] :

Pattern.matches("a*|[mn]", "aaaa")

Live example :

import java.util.regex.Pattern;

class Example {
    public static void main (String[] args) throws java.lang.Exception {
        check("aaaa", true);
        check("a", true);
        check("", true);
        check("m", true);
        check("n", true);
        check("mn", false);
        check("q", false);
        check("nnnn", false);
    }
    private static void check(String text, boolean expect) {
        boolean result = Pattern.matches("a*|[mn]", text);
        System.out.println(
            (result ? "Match   " : "No match") +
            (result == expect ? " OK    " : " ERROR ") +
            ": " + text
        );
    }
}

...though obviously if you were really using the pattern repeatedly, you'd want to compile it once and reuse the result.

Try this regex

(a*)|m|n
Pattern.matches("(a*)|m|n", "") // true, match 1st group
Pattern.matches("(a*)|m|n", "a") // true, match 1st group
Pattern.matches("(a*)|m|n", "aaaa") // true, match 1st group
Pattern.matches("(a*)|m|n", "m") // true, match `n`
Pattern.matches("(a*)|m|n", "n") // true, match `m`
Pattern.matches("(a*)|m|n", "man") // false
Pattern.matches("(a*)|m|n", "mn") // false

inside the [] the " " is not a quantifier so you'll get a true if one of the characters in the regex is present therefore the result will be true if the string is "a"," ","m" or "n". And the rest will result in false. your regex should be:

([aa*]*|[mn])

it will be true only if multiples of "a" are entered including "a*" or a single "m" or "n". check it by following examples:

System.out.println("[aa*]*|[mn]","m");
System.out.println("[aa*]*|[mn]","aaaaa");
System.out.println("[aa*]*|[mn]","a*a*");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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