Java - 通过多行正则表达式匹配第一个字符串

我目前正在构建一个 java 程序来自动化每周定期的体育课预订,而不是手动预订。


为了实现这一点,我通过 http get 加载特定日期的类列表,并希望从响应中解析所需的类 id (foo/bar/ class-id )。


缩短的响应如下所示:


<div>

    <div class="row">

            Olympic Weightlifting <br>


            <a data-url="foo/bar/2099159">

                Book

            </a>

    </div>

    <div class="row">

            Fitness <br>


            <a data-url="foo/bar/2098939">

                Book

            </a>

    </div>

</div>

到目前为止,下面片段中的两个正则表达式是我能得到的最接近的,但它们都将匹配最后一个/第二个类 id,而不是“Weightlifting”这个词之后的第一个。


    String str = "<div>\n" +

            "\t<div class=\"row\">\n" +

            "\t\t\tOlympic Weightlifting <br>\n" +

            "\n" +

            "\t\t\t<a data-url=\"foo/bar/2099159\">\n" +

            "\t\t\t\tBook\n" +

            "\t\t\t</a>\n" +

            "\t</div>\n" +

            "\t<div class=\"row\">\n" +

            "\t\t\tFitness <br>\n" +

            "\n" +

            "\t\t\t<a data-url=\"foo/bar/2098939\">\n" +

            "\t\t\t\tBook\n" +

            "\t\t\t</a>\n" +

            "\t</div>\n" +

            "</div>";



    // regex 1: pattern multiline

    Pattern p = Pattern.compile("Weightlifting.*foo/bar/(.*?)\"", Pattern.DOTALL);

    // regex 2: inline multiline

    // Pattern p = Pattern.compile("Weightlifting[\\s\\S]*foo/bar/(.*?)\"");

    Matcher m = p.matcher(str);


    if (m.find()) {

        System.out.println(m.group(1).trim());

    }


皈依舞
浏览 295回答 1
1回答

郎朗坤

好吧,你的正则表达式很贪婪,你需要让它变得懒惰。&nbsp;"Weightlifting.*?foo/bar/(.*?)\""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^ change this part您可以使用的另一种模式是(?<=data-url=")[^\/]+\/[^\/]+\/(\d+)(?<=data-url\s*=\s*")- 积极的回顾。检查data-url=[^\/]+\/[^\/]+\/- 最多匹配两个文本/。(\d+)- 匹配数字一次或多次(您要捕获的 id)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java