java - 为什么 Pattern.matches ("[a*mn]","aaaa") 不返回 true?获得所需输出的正确代码应该是什么?

标签 java

我想创建一个模式,其中所需的字符串应该是 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")

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
        );
    }
}

...虽然很明显,如果您真的重复使用该模式,您会希望编译一次并重用结果。

关于java - 为什么 Pattern.matches ("[a*mn]","aaaa") 不返回 true?获得所需输出的正确代码应该是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57345958/

相关文章:

Java:以下是类还是对象?

java - 从嵌套 JAR 加载 Velocity 模板

java - 创建这个自定义的、可重用的 View

Java匹配数组

java - 在spark中访问 vector 的元素

java - 如果 JUnit 测试失败则停止测试

java - main 中的数组引用 main 之外的数组

java - 使用java获取hdfs namenode的状态

java - 如何在 android 中使用 DateFormat.getDateTimeInstance() 仅显示当前时间

Java 线程,从主 JFrame GUI 关闭服务器线程