Reputation: 31
I want to create a pattern where the desired string should either be multiples of a including null i.e. 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"));
}
}
Upvotes: 1
Views: 126
Reputation: 32
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*");
Upvotes: 1
Reputation: 1074248
*
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 i.e. 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")
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.
Upvotes: 4
Reputation: 4474
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
Upvotes: 1