【问题标题】:Java Regex - multiple urls match in one output stringJava Regex - 在一个输出字符串中匹配多个 url
【发布时间】:2020-05-31 20:32:39
【问题描述】:

我有这个字符串:

jwplayer("vplayer").setup({sources:[{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4",label:"720p"},{file:"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4",label:"360p"}],image:"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg"

我只想获取两个网址,即file: 之后的网址。 所需的输出 string 应该是这样的:

https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4, https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4

我怎样才能在java中得到这个?

我已经尝试过这个正则表达式:"file:\"(.*?)\"",但我只得到了第一个 url,即使我已经将 matcher.find() 放在了一个 while 循环中。

编辑: 这个正则表达式也适用于@azro 答案中的那个。我的问题是 while 循环中的某些代码会引发错误并在一次迭代后停止循环(感谢@pafau_k)。 很抱歉给您带来不便。。

【问题讨论】:

  • 你试过了吗?
  • 当你手头有一个 json 时,也许只是解析 json?这是一回事,另一回事:到目前为止,您尝试了什么?你被困在哪里了?你至少试过answers to similar questions?
  • 我已经尝试过这个正则表达式: "file:\"(.*?)\"" ,但即使我已经将 matcher.find() 放在了 while 循环中,我也只有第一个 url .
  • 这是一个很好的正则表达式(甚至比答案中的那个更好,因为它还会找到除 https 协议之外的其他内容)。它对我来说可以正常工作,也许将您的代码与循环一起发布(编辑问题),以便我们找到错误?或者只是从 azro 的答案中复制 while 循环,应该可以正常工作。
  • Yiu 在 file: 之后说想要 URL,但在那之后是引号“,是 url 的一部分吗?url 验证是什么需要?看起来不像这样。试试 findall事情(?<=file:").*?(?=")

标签: java regex


【解决方案1】:

要获得像这个文件这样的简单正则表达式的网址:"(https.*?)" 会起作用,*? 表示尽可能多的,在第一次引用之后停止

String content = "jwplayer(\"vplayer\").setup({sources:[{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4\",label:\"720p\"},{file:\"https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4\",label:\"360p\"}],image:\"https://v5.vidhd.net/i/01/00007/vdachffyt692.jpg\"";

Matcher m = Pattern.compile("file:\"(http.*?)\"").matcher(content);
while(m.find())
    System.out.println(m.group(1));

同时采集的流版本

String res = Pattern.compile("file:\"(http.*?)\"")
                    .matcher(content)
                    .results()
                    .map(r -> r.group(1))
                    .collect(Collectors.joining(" "));

System.out.println(res); // https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmtbfbdks3bqofp5s6incq/v.mp4 https://v5.vidhd.net/kmxsus4zpjumwmesrlwey575ndnsv4xwfgemw6pmt2xbbks3bqofaojtzsgq/v.mp4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-23
    • 2013-07-04
    • 2014-08-05
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多