REGEX匹配字符串在或之后,并且每组仅返回一个匹配项



我正在尝试从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]和Movie [id]放在比赛中,而不仅仅是一个。我正在寻找的是使用Movieid_ [id]并将Movie [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[^>]*>?.*?";

任何帮助将不胜感激。谢谢!

对于第一个问题,请检查下面...

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

为了使它起作用,您的Java代码将为

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));
    }
}

REGEX的演示。


第二个条件更新

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

REGEX的演示


说明

.*?<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 !!!


更新2

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

在这里,我引入了尾随hasAudio(如果有)的条件。请注意,在这条正则匹配中,整个匹配是电影ID,没有组。

我们在这里使用的主要功能是 k标志,该 k标志将匹配位置重置为当前。在那里放下所有以前都从比赛中抓起的炭。这有助于我们绕过可变长度的外观。

演示在这里

最新更新