2017-10-04 111 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

相关问题