正则表达式:在前瞻之前捕获第一次出现
发布时间:2020-12-14 06:04:22 所属栏目:百科 来源:网络整理
导读:我试图在特定单词之前捕获网址.唯一的麻烦是这个词也可能是域的一部分. 示例:(我试图在晚餐前捕获所有东西) https://breakfast.example.com/lunch/dinner/https://breakfast.example.brunch.com:8080/lunch/dinnerhttp://dinnerdemo.example.com/dinner/ 我
我试图在特定单词之前捕获网址.唯一的麻烦是这个词也可能是域的一部分.
示例:(我试图在晚餐前捕获所有东西) https://breakfast.example.com/lunch/dinner/ https://breakfast.example.brunch.com:8080/lunch/dinner http://dinnerdemo.example.com/dinner/ 我可以使用: ^(.*://.*/)(?=dinner/?) 我遇到的麻烦是前瞻性似乎不够懒惰 https://breakfast.example.com/lunch/dinner/login.html?returnURL=https://breakfast.example.com/lunch/dinner/ 因为它捕获: https://breakfast.example.com/lunch/dinner/login.html?returnURL=https://breakfast.example.com/lunch/ 我都不明白为什么以及如何修复我的正则表达式. 解决方法
你可以使用一些懒惰:
^(.*?://).*?/(?=dinner/?) Live demo 通过在正则表达式的中间使用.*,你可以吃掉所有内容,直到找到匹配的最后一个冒号. 顺便说一句,在正则表达式的中间,是非常糟糕的做法.它可能会导致长串中可怕的回溯性能下降. .*?更好,因为它不情愿而不是贪婪. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |