2011-09-07 72 views
1

我打開了一個filters.txt文件。下面是該文件:將圖案與網址匹配

http://www.somehost.com/.*/releases, RE,TO 

我比較文本文件中的第一個條目與我的代碼中的硬編碼的網址。任何以文本文件中的模式(首字母)開頭的URL都應該這樣做,尤其是在循環中。這裏這個URL http://www.somehost.com/news/releases/2011/09/07/somehost-and-life-care-networks-launch-3g-mobile-health-project-help-patien是源於這種模式的網址只有http://www.somehost.com/.*/releases。但它仍然不符合這種模式。任何建議爲什麼會發生?

BufferedReader readbuffer = null; 
      try { 
       readbuffer = new BufferedReader(new FileReader("filters.txt")); 
      } catch (FileNotFoundException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
      String strRead; 



     try { 
      while ((strRead=readbuffer.readLine())!=null){ 
       String splitarray[] = strRead.split(","); 
       String firstentry = splitarray[0]; 
       String secondentry = splitarray[1]; 
       String thirdentry = splitarray[2]; 



       Pattern p = Pattern.compile("^" +firstentry); 
       Matcher m = p.matcher("http://www.somehost.com/news/releases/2011/09/07/somehost-and-life-care-networks-launch-3g-mobile-health-project-help-patien"); 

       if (m.find() && thirdentry.startsWith("LO")) { 
        //Do whatever 

        System.out.println("First Loop"); 

       } 

       else if(m.find() && thirdentry.startsWith("TO")) 
       { 
        System.out.println("Second Loop"); 
       } 

       } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
+0

您能否明確提供您的正則表達式和需要匹配的URLS樣本? –

+0

@Benjamin ..我已經提供了上面的文本文件...該文本文件有一個條目,如上所述...我首先測試該網址..任何URL開始與文本文件中的模式url應該做什麼,如果循環 – AKIWEB

回答

0

試着分開find()和你的if/else。您需要在for循環中只撥打find()一次。

Javadoc說: Matcher.find() Attempts to find the next subsequence of the input sequence that matches the pattern.接下來是非常重要的,這意味着每次調用該方法時跳到下一個可能的匹配。

boolean found = m.find(); 
if (found && thirdentry.startsWith("LO")) { 
//Do whatever 
    System.out.println("First Loop"); 
} 
else if(found && thirdentry.startsWith("TO")) 
{ 
    System.out.println("Second Loop"); 
} 
+0

我沒有意識到這一點..感謝指出這對我..現在它的工作.. – AKIWEB