V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
JavaFirstMaster
V2EX  ›  问与答

Java 语言有个简单的正则不会写了...

  •  
  •   JavaFirstMaster · 2020-01-06 15:10:07 +08:00 · 1306 次点击
    这是一个创建于 1575 天前的主题,其中的信息可能已经有所发展或是发生改变。
    public class SimpleTest {
    
        @Test
        public void test() {
            String s = "https://www.baidu.comhttp://abc.com/abc.jpg";
            Matcher matcher = Pattern.compile("https?://.+").matcher(s);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
    

    如上代码, 我想把字符串分割成两个正确的 url, 可是上面的正则始终是"贪婪模式", 一下子匹配到整个字符串.

    如果正则写成 https?://.+?, 又只会匹配到如下结果:

    • https://w
    • http://a

    有没有帅气堪比吴彦祖的朋友解答一下我的疑惑呀

    4 条回复    2020-01-06 17:16:42 +08:00
    iyaozhen
        1
    iyaozhen  
       2020-01-06 15:33:37 +08:00   ❤️ 1


    https?:\/\/.+?(?=http|$)

    有个非常拗口的翻译:零宽断言 https://deerchao.cn/tutorials/regex/regex.htm#lookaround
    JavaFirstMaster
        2
    JavaFirstMaster  
    OP
       2020-01-06 16:04:44 +08:00
    @iyaozhen 非常正确!

    我之前想到这个了, 不过差了一点, 我写的是 `https?://.+(?=https?://|$)`, 外部的 `.+` 后面没有指定非贪婪模式!

    谢谢吴彦祖!!
    optional
        3
    optional  
       2020-01-06 16:46:29 +08:00
    这个需求直接 split( http)似乎更好啊。
    JavaFirstMaster
        4
    JavaFirstMaster  
    OP
       2020-01-06 17:16:42 +08:00
    @optional 字符串中包含的网址数量不定, 而且 http 或者 https 位置也不确定, 所以 split 的话比较麻烦
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3080 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:19 · PVG 21:19 · LAX 06:19 · JFK 09:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.