2017-03-02 18 views
-1

我有一個大字符串,我想從該字符串中取得鏈接。我可以打印鏈接。從replace取代變量全部

Pattern pattern = Pattern.compile(".*(?<=overlay-link\" href=\").*?(?=\">).*"); 

與該代碼。輸出示例:

<a title="TITLE" class="overlay-link" href="LINK HERE"></a> 

當我嘗試string.replaceAll,正則表達式刪除鏈接並打印另一個變量。

EX: <a title="TITLE" class="overlay-link" href=""></a> 

我是新的正則表達式。你可以幫我嗎?

這裏是全碼:

String content;  
Pattern pattern = Pattern.compile(".*(?<=overlay-link\" href=\").*?(?=\">).*"); 

try { 
    Scanner scanner = new Scanner(new File("sourceCode.txt")); 
    while (scanner.hasNext()) { 
     content = scanner.nextLine(); 
     if (pattern.matcher(content).matches()) {  
      System.out.println(content.replaceAll("(?<=overlay-link\" href=\").*?(?=\">)", "")); 
     } 
    } 
} catch (IOException ex) { 
    Logger.getLogger(SourceCodeExample.class.getName()).log(Level.SEVERE, null, ex); 
} 
+1

不要使用正則表達式解析XML或HTML。請參閱http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-reg – VGR

+0

但我必須使用正則表達式 –

回答

0

如果我理解你的問題正確,您正在考慮退出只是在href標記指定的鏈接。

要做到這一點,你應該在你的正則表達式本身中使用捕獲組,而不是嘗試replaceAll。

replaceAll方法正確地找到鏈接並用空字符串替換它,並根據docs返回完整的結果字符串,這不是所需的結果。

你應該使用的正則表達式是這樣的:.*(?<=overlay-link\" href=\")(.*?)(?=\">).*注意鏈接周圍的捕獲組()。

這將允許您找到匹配並訪問捕獲組1.我發現了一個很好的示例,說明如何在其他question中執行此操作。 (重要片段粘貼以下),由我添加

String line = "This order was placed for QT3000! OK?"; //<a> tag string 
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)"); //insert regex provided above 
Matcher matcher = pattern.matcher(line); 
while (matcher.find()) { 
    System.out.println("group 1: " + matcher.group(1)); //This will be your link 
    System.out.println("group 2: " + matcher.group(2)); 
    System.out.println("group 3: " + matcher.group(3)); 
} 

評論

注:指數0表示整個Pattern