gpt4 book ai didi

java - 模式编译 .*?对比*

转载 作者:行者123 更新时间:2023-11-30 08:44:19 25 4
gpt4 key购买 nike

我发现了不同,但我无法解释:

public static void main(String[] args) {
Pattern p = Pattern.compile("[+-]?\\d+.*?");
Matcher m = p.matcher("+5.0h");
System.out.println(m.matches()); //prints true

Scanner in = new Scanner("+5.0h");
while (in.hasNext()) {
if (in.hasNext(p)) {
System.out.println(in.findInLine(p)); //prints +5
}
}
in.close();

System.out.println("6.0hgf".matches("[+-]?\\d+.*?")); //prints nothing,it seemed that this sentence didn't execute,why this happened?
}

当我变了

Pattern p = Pattern.compile("[+-]?\\d+.*?")

Pattern p = Pattern.compile("[+-]?\\d+.*")

发生了以下情况:

public static void main(String[] args) {
Pattern p = Pattern.compile("[+-]?\\d+.*");
Matcher m = p.matcher("+5.0h");
System.out.println(m.matches()); //prints true

Scanner in = new Scanner("+5.0h");
while (in.hasNext()) {
if (in.hasNext(p)) {
System.out.println(in.findInLine(p)); //prints +5.0h
}
}
in.close();

System.out.println("6.0hgf".matches("[+-]?\\d+.*?")); //prints true
}

所以我想知道为什么会这样?

最佳答案

* 的默认行为是尽可能多地匹配,在它之后放置一个 ? 以确保只匹配必要的数量。

例如:

如果我有字符串 "abc" 并且我使用 .* ,它将匹配整个字符串,但是如果我将正则表达式更改为 .*? 它不会匹配任何东西,因为 * 是 0 或更多。

我们还可以以 + 为例,如果字符串再次为 "abc" 并且正则表达式为 .+ 它将匹配整个字符串,但如果正则表达式是 .+? 它将只匹配一个字符,在本例中为 a.

关于java - 模式编译 .*?对比*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33840802/

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