2016-11-22 68 views
0

这是我的映射器中的代码。映射器的错误正则表达式

result.put("contentThumbUrl", getThumbUrl(extractor.extract("youtube.videolink").asText(), false)); 
      result.put("contentThumbSmallUrl", getThumbUrl(extractor.extract("youtube.videolink").asText(), true)); 

我的功能是:

private String getThumbUrl(String videoId, boolean small) { 
     videoId = videoId.replaceAll("http://www\\.youtube\\.([a-z]{2}|[a-z]{3})/watch\\?v=.|https://www\\.youtube\\.([a-z]{2}|[a-z]{3})/watch\\?v=", ""); 
     if(small) { 
      return "http://img.youtube.com/vi/" + videoId + "/2.jpg"; 
     } 
     return "http://img.youtube.com/vi/" + videoId + "/0.jpg"; 
    } 

但是我得到了错误的结果。

"contentThumbSmallUrl":"http:\/\/img.youtube.com\/vi\/https:\/\/www.youtube.com\/watch?v=lEBwKBJ8Leg\/2.jpg" 
and 
contentThumbUrl":"http:\/\/img.youtube.com\/vi\/https:\/\/www.youtube.com\/watch?v=lEBwKBJ8Leg\/0.jpg" 

有反正我可以改正它。我不知道我的正则表达式是否正确。有什么方法可以缩短我的正则表达式吗?

回答

0

我不知道为什么它在文本上失败。它看起来很奇怪,但是斜线(\/)。只需要反斜杠(\)。你应该检查你的输入。

我看到的正则表达式唯一的问题是在上半场之后的一个无关期间(.):\\?v=.|https://。它会从视频ID中删除多余的字符。

为了缩短模式,你可以这样做:

"http(s)?://www\\.youtube\\.([a-z]{2,3})/watch\\?v=" 

括号是可选的,但艾滋病可读性。

演示:https://regex101.com/r/9gRG8Q/1