2016-05-05 22 views
0
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()方法的這種行爲。在java中發現Matcher的find()方法的意外行爲

+2

沒有什麼意外的在這裏,它在[API文檔]怎麼解釋(http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#find--)。 – biziclop

回答

2

docs

公共布爾find()方法 試圖查找與該模式匹配的輸入序列的下一個子。 這種方法始於此匹配的區域的開始,或者,如果方法以前調用成功並且匹配以來沒有被重置,在沒有由以前匹配匹配的第一個字符。

+0

所以,如果你在'indiaindiaindia'通,'找到()'在到達字符串結束前返回TRUE;三次。 – biziclop

0

find()方法將搜索特定的模式,如果它發現它返回true,但是,如果你再打電話find(),它繼續尋找從點開始在該字符串。在那裏,你會得到錯誤的bcz,它找不到它。

如果使用find(int location)你可以告訴它在字符串中搜索,從而讓您找到相同的圖案,很多次,只要你喜歡。

+0

感謝名單爲您的建議@ blahfunk,@ nateyolles,@ biziclop –