2011-09-02 49 views
-3

我有一個包含以下形式薈萃URL的文本文件:如何匹配文本文件中的模式列表中的url?

http://www.xyz.com/.*services/ 
http://www.xyz.com/.*/wireless 

我想從這個文件中的模式與我的URL進行比較,如果我找到一個匹配執行相應的操作。這個匹配過程對我來說很難理解。

假設splitarray [0]包含文本文件的第一行:

  String url = page.getWebURL().getURL();   
      URL url1 = new URL(url); 

我們如何能夠比較URL1與splitarray [0]?

修訂

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]; 
       //String fourthentry = splitarray[3]; 
       //String fifthentry = splitarray[4]; 
       System.out.println(firstentry + " " + secondentry+ " " +thirdentry); 
       URL url1 = new URL("http://www.xyz.com/ship/reach/news-and"); 

       Pattern p = Pattern.compile("http://www.xyz.com/.*/reach"); 
       Matcher m = p.matcher(url1.toString()); 

       if (m.matches()) { 
        //Do whatever 
        System.out.println("Yes Done"); 
       } 



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

匹配工作正常......但是,如果我想這裏面有圖案的splitarray給予啓動任何網址[0],然後做到這一點......我們如何能夠實現這...在上面的情況下,它不匹配,但這個網址http://www.xyz.com/ship/w是從這種模式只http://www.xyz.com/.*/reach因此,任何網址,以這種模式開始..只是在if循環中做這件事...任何建議將不勝感激。 .. !!

回答

1

我很困惑,正則表達式來自哪裏。文本文件?無論如何,你將很難將url1與任何正則表達式進行比較,因爲它是URL對象,並且正則表達式比較字符串。所以你會想要堅持使用你的String url

試試這個:

Pattern p = Pattern.compile(splitarray[0]); 
Matcher m = p.matcher(url); 

if (m.matches()) { 
    //Do whatever 
} 

m.matches()方法檢查您提供整個字符串是否與模式,這可能是你想要的這裏比賽。如果您需要檢查部分字符串是否匹配,請改用m.find()

更新

既然你只希望匹配的字符串開頭的模式,你需要使用m.find()代替。特殊字符^只在字符串開始處匹配,這樣添加到你的正則表達式的前面,例如:

Pattern p = Pattern.compile("^" + splitarray[0]); 

+0

見上面我的更新。 – andronikus

+0

也許你會考慮接受我的答案,因爲它解決了你的問題? – andronikus

2

你在這裏失蹤了一步。您首先需要將您的網址翻譯爲正則表達式,或者設計一個使用這些網址的方法,然後才能將您的網址url1與這些模式進行比較。

根據你所顯示的模式,我假設你正在爲xyz解決方案設計軟件,就像他們的路由器一樣。因此,您的網址應該落在一個簡單的圖案風格,像 http://www.xyz.com/正則表達式,這裏

相關問題