2011-11-08 16 views
0

我想從一個文件中的每一行讀取和編輯只能從特定服務器提供的URL行...我的代碼是這樣......java模式

Scanner ReadIsbn = new Scanner (new FileReader ("C:/Users/...."));   

    Pattern pat = Pattern.compile("http:////www.librarything.com//isbn//"); 

    while (ReadIsbn.hasNextLine()){ 

     String line = ReadIsbn.nextLine(); 
     Matcher m = pat.matcher(line); 
     if (m.matches() == true) { 
      EDIT line.... 

     } 

    } 

} 

它是不工作...其實m.matches()始終是假的.. 在我給作爲輸入文件,有喜歡的臺詞:

1) http://www.librarything.com/isbn/0-9616696-7-5.html 
2) http://www.librarything.com/isbn/0-86078-322-7.html 
Cultural tourism : how the arts can help market tourism products, how 
blablabla 

(我想編輯只的前兩行例如)

回答

2

你不需要escap e在你的模式中向前斜線。這應該做

Pattern pat = Pattern.compile("http://www.librarything.com/isbn/"); 

另一個問題是,matches方法試圖來匹配整個輸入文本模式。使用

if (m.find()){ 
     EDIT line.... 
} 

如果你只是要檢查,你在這裏做前綴,那麼你也可以使用String#startsWith方法

1

它不工作,因爲方法matches()匹配線。您應該添加.*到您的模式結束

Pattern pat = Pattern.compile("http://www.librarything.com//isbn/.*");

或使用方法的「find()」來代替。

此外,你不應該寫重複的正斜槓。這個字符'/'是前進的,而不是反斜槓。