我发现了差异,但无法解释:
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/