gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:48:39 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com