JSON格式URL列表的Java Regex模式



我在为需要匹配的内容找到正确的正则表达式时遇到了一些问题。

源代码如下:

"url240":"https:\/\/domain.com\/id123456\/files\/video.240.mp4?extra=hash"
,"url360":"https:\/\/domain.com\/id123456\/files\/video.360.mp4?extra=hash"
,"url480":"https:\/\/domain.com\/id123456\/files\/video.480.mp4?extra=hash"
,"url720":"https:\/\/domain.com\/id123456\/files\/video.720.mp4?extra=hash"

我需要匹配所有url(可以是一个、两个、三个或全部四个,这取决于提供给应用程序的源代码),并将它们存储在ArrayList上。

这是我通常使用的代码:

List<String> sourceList = new ArrayList<String>();
Pattern vPattern = Pattern.compile(?);
Matcher videoMatcher = vPattern.matcher(source);
while (videoMatcher.find())
    sourceList.add(videoMatcher.group(2));

但是我通常使用的模式不能在这种情况下使用。

我尝试过:

\"urld+\":\"(.*?)\"

但它不起作用。

对于您列出的源,您的表达式是正确的。这个问题与字符串转义有关。

在Java中使用表达式时,我们在使用字符串之前要对其进行两次解析,第一次是在创建Java字符串时,第二次是由正则表达式引擎进行解析,您匹配的是"url[0-9]+":"(.*?)",您已经完成了第一级转义(对于正则表达式引擎)。接下来,我们需要再次为Java转义字符串。

因此,为了获得您发布的表达式,我们需要转义所有的,以便它们在最终字符串中成为,并且不会被Java作为转义序列处理。我们需要转义"的,因为整个字符串是一个字符串,未转义的"终止了该字符串。

这意味着我们需要用作为所有"的前缀,这可以在任何编辑器中使用搜索和替换来轻松完成,只要我们用\替换,然后用"替换",因为我们不想在转义"时转义添加的

这给了我们:"\\"url\d+\\":\\"(.*?)\\""

除此之外,表达式只有一个匹配组,因此我们需要得到videoMatcher.group(1)而不是videoMatcher.group(2)

测试代码:

public static void main(String[] args) throws Exception {
    String source = "\"url240\":\"https:\\\/\\\/domain.com\\\/id123456\\\/files\\\/video.240.mp4?extra=hash\",n\"url360\":\"https:\\\/\\\/domain.com\\\/id123456\\\/files\\\/video.360.mp4?extra=hash\",n\"url480\":\"https:\\\/\\\/domain.com\\\/id123456\\\/files\\\/video.480.mp4?extra=hash\",n\"url720\":\"https:\\\/\\\/domain.com\\\/id123456\\\/files\\\/video.720.mp4?extra=hash\"";
    String pattern = "\\"url\d+\\":\\"(.*?)\\"";
    System.out.println("Source: " + source);
    System.out.println("nPattern: " + pattern);
    List<String> sourceList = new ArrayList<String>();
    Pattern vPattern = Pattern.compile(pattern);
    Matcher videoMatcher = vPattern.matcher(source);
    while (videoMatcher.find()) {
        sourceList.add(videoMatcher.group(1));
    }
    System.out.println("nResult:" + Arrays.toString(sourceList.toArray(new String[0])));
}

输出:

Source: "url240":"https:\/\/domain.com\/id123456\/files\/video.240.mp4?extra=hash",
"url360":"https:\/\/domain.com\/id123456\/files\/video.360.mp4?extra=hash",
"url480":"https:\/\/domain.com\/id123456\/files\/video.480.mp4?extra=hash",
"url720":"https:\/\/domain.com\/id123456\/files\/video.720.mp4?extra=hash"
Pattern: \"urld+\":\"(.*?)\"
Result:[https:\/\/domain.com\/id123456\/files\/video.240.mp4?extra=hash, https:\/\/domain.com\/id123456\/files\/video.360.mp4?extra=hash, https:\/\/domain.com\/id123456\/files\/video.480.mp4?extra=hash,     https:\/\/domain.com\/id123456\/files\/video.720.mp4?extra=hash]

正如我们所看到的,一旦模式字符串被取消转义一次,它的值就是我们想要的正则表达式。

最新更新