我有以下代码:

String responseData = "http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";
"http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";

String pattern = ^(https://.*\.54325)$;

Pattern pr = Pattern.compile(pattern);

            Matcher math = pr.matcher(responseData);


            if (math.find()) {

            // print the url

            }
            else {
                System.out.println("No Math");
            }


我想打印出以http开头并以.m3u8结尾的最后一个字符串。我该怎么做呢?我被卡住了。感谢所有帮助。

我现在遇到的问题是,当我找到一个数学公式以及要打印出什么内容的字符串时,我从responseData中得到了所有东西。

最佳答案

万一您需要在末尾得到一些类似的子字符串之前的子字符串,则需要确保正则表达式引擎在所需的匹配之前已经消耗了尽可能多的字符。

另外,您的模式中有一个^表示beginning of a string。因此,它从一开始就开始匹配。

您只需使用lastIndexOfsubstring即可实现所需的功能:

System.out.println(str.substring(str.lastIndexOf("http://")));


或者,如果您需要正则表达式,则需要使用

String pattern = ".*(http://.*?\\.m3u8)$";


并使用math.group(1)打印该值。

Sample code

import java.util.regex.*;
public class HelloWorld{

     public static void main(String []args){

        String str = "http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_0_av.m3u8" +
"EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2795000,RESOLUTION=1280x720,CODECS=avc1.64001f, mp4a.40.2" +
"http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8";
        String rx = ".*(http://.*?\\.m3u8)$";
        Pattern ptrn = Pattern.compile(rx);
        Matcher m = ptrn.matcher(str);
        while (m.find()) {
            System.out.println(m.group(1));
        }
     }
}


输出:

http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8


Also tested on RegexPlanet

关于java - 打印出正则表达式的最后一个匹配项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29912992/

10-12 07:38
查看更多