gpt4 book ai didi

java - 发现 java 中 Matcher 的 find() 方法出现意外行为

转载 作者:行者123 更新时间:2023-12-02 03:39:08 26 4
gpt4 key购买 nike

public class Test2 {

public static void main(String[] args)
{
String country="india";
String arry[]={"indians are great","i am india","govt","dhoomindian","prashindiahim","i jdsdindi a","i n d i a"};
Pattern p = Pattern.compile(".*" + country + ".*");
for (String stringVal : arry)
{
Matcher m = p.matcher(stringVal);
System.out.println("test1..."+" -->"+stringVal+" "+m.find());
System.out.println("test2..."+" -->"+stringVal+" "+m.find());
}
}
}


OUTPUT::

*test1... -->indians are great true* ----1
**test2... -->indians are great false**-----2
*test1... -->i am india true* ----3
**test2... -->i am india false** ---4
test1... -->govt false
test2... -->govt false
test1... -->dhoomindian true----5
test2... -->dhoomindian false----6
test1... -->prashindiahim true----7
test2... -->prashindiahim false----8
test1... -->i jdsdindi a false
test2... -->i jdsdindi a false
test1... -->i n d i a false
test2... -->i n d i a false

您可以看到相同的 find() 方法在第一行中给出 true,在前面的第二行中给出 false。您可以从第 1-8 行看到行为。谁能告诉我为什么我会遇到 find() 方法的这种行为。

最佳答案

来自docs

public boolean find() Attempts to find the next subsequence of the input sequence that matches the pattern. This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

关于java - 发现 java 中 Matcher 的 find() 方法出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052189/

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