2017-10-04 109 views
0

我試圖從HTML代碼中獲取某些ID。我有一些工作,但我需要幫助的其他事情。下面是視頻部分的HTML代碼示例:正則表達式匹配字符串之前或之後,並且每個集合只返回一個匹配

<video id="movie1" class="show_movie-camera animation_target movieBorder hasAudio movieId_750" src="/path/to/movie" style="position: absolute; z-index: 505; top: 44.5px; left: 484px; display: none;" preload="true" autoplay="true"></video> 
<video id="movie2" class="clickInfo movieId_587" src="/path/to/movie" preload="true" autoplay="true"></video> 
<video id="movie300" src="/path/to/movie" preload="true" autoplay="true"></video> 

爲了得到影片的ID,我找movieId_ [ID]或電影[ID]使用此正則表達式:

.*?<object|<video.*?movie(\\d+)|movieId_(\\d+)[^>]*>?.*? 

這種運作良好,但它將movieId_ [ID]和電影[ID]放在匹配中,而不僅僅是一個。我正在尋找的是使用movieId_ [ID]並使用電影[ID]作爲後備。這是我用:

Pattern p = Pattern.compile(regex); 
Matcher m = p.matcher(content); 
int fileId = -1; 
while(m.find()) { 
    fileId = -1; 
    if (m.group(2) != null) { 
     fileId = new Integer(m.group(2)); 
    } else if (m.group(1) != null) { 
     fileId = new Integer(m.group(1)); 
    } 
} 

這會給我1,750,2,587,300,而不是750,578,300,我期待的。

此外,我正在尋找具有hasAudio類的比賽。這是我試圖沒有成功:

.*?<object|<video.*?hasAudio.*movieId_(\\d+)|movieId_(\\d+).*hasAudio[^>]*>?.*?"; 

任何幫助,將不勝感激。謝謝!

+0

是的,對不起,已被更正。 – fanfavorite

+6

[你不應該使用正則表達式來解析HTML](https://stackoverflow.com/a/1732454/6073886) –

+0

更好地使用類似jsoup的東西? HTML是數據庫表中的內容,被拉取並處理。 – fanfavorite

回答

2

對於第一個問題檢查以下...

.*?<object|<video[^>]*((?<=movieId_)\d+|(?<=movie)\d+) 

要使其工作Java代碼將正則表達式here

Pattern p = Pattern.compile(regex); 
Matcher m = p.matcher(content); 
int fileId = -1; 
while(m.find()) { 
    fileId = -1; 
    if (m.group(1) != null) { 
     fileId = new Integer(m.group(1)); 
    } 
} 

演示。


更新第二條件

.*?<object|<video[^>]*hasAudio[^>]*((?<=movieId_)\d+|(?<=movie)\d+) 

正則表達式的演示here


說明

.*?<object     //Already existing regex 
|       //OR capture the movie ID as below 
<video[^>]*hasAudio[^>]* //Part of full match include all characters except '>' 
          //This makes sure matches do not go beyond the tag 
          //Also makes sure that hasAudio is part of this string 
(       //START: Our Group1 capture as Movie ID 
(?<=movieId_)\d+   //First try getting id out of moviedId_xxx 
|       //OR if first fails 
(?<=movie)\d+    //Second try getting id out of moviexxx 
)       //END: Our Group1 capture as Movie ID 

注意:.*?<object將永遠只匹配<object !!!


UPDATE 2

<object|<video[^>]*\K(?:hasAudio[^>]*\K(?:(?<=movieId_)\d+|(?<=movie)\d+)|(?:(?<=movieId_)\d+|(?<=movie)\d+)(?=[^>]*hasAudio)) 

在這裏,我介紹了條件後hasAudio如果有的話。請注意,在此正則表達式中,完整匹配是movieID,不會有組。

我們這裏使用的主要功能是\ K標誌,它將匹配位置重置爲當前。通過放棄所有以前抓住的比賽中的所有字符。這有助於我們解決可變長度後視。

演示here

+0

我正在使用jsoup來解析HTML,但這是一個很好的正則表達式解決方案並且回答了這個問題。謝謝! – fanfavorite

相關問題