2011-09-07 73 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