我想创建一个模式,其中所需的字符串应该是 a 的倍数,包括 null,即 a*,或者它应该是一个 m 或一个 n。但是下面的代码没有给出所需的输出。
class Solution {
public static void main(String args[]) {
System.out.println(Pattern.matches("[a*mn]", "aaaa"));
}
}
最佳答案
字符类 ([]
) 中的
*
只是一个 *
,不是量词。
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.
为此你需要一个替代 (|
):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
);
}
}
...虽然很明显,如果您真的重复使用该模式,您会希望编译一次并重用结果。
关于java - 为什么 Pattern.matches ("[a*mn]","aaaa") 不返回 true?获得所需输出的正确代码应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57345958/