我正在尝试将 URL 上的文件扩展名与图像相匹配。我有这个正则表达式:
(?<=\.)(jpe?g|png|gif|bmp|tga|tiff)$
我已经在几个网站上对此进行了测试,它匹配得很好。但是当我尝试在 Java 中使用它时,我添加了一个额外的\来转义 .我认为我不需要添加更多内容?但这不起作用:
Pattern extensionPat = Pattern.compile("(?<=\\.)(jpe?g|png|gif|bmp|tga|tiff)$", Pattern.CASE_INSENSITIVE);
Matcher findExtension = extensionPat.matcher(imageURL);
String extension = findExtension.group();
其中 imageURL 为“https://www.google.com/images/srpr/logo4w.png”
根据同事的建议,我也尝试将管道逃逸到:
Pattern extensionPat = Pattern.compile("(?<=\\.)(jpe?g\\|png\\|gif\\|bmp\\|tga\\|tiff)$", Pattern.CASE_INSENSITIVE);
我尝试转义 $ 和 <,但似乎没有任何效果...
最佳答案
您需要调用findExtension.find()
首先,否则 findExtension.group()
不返回任何内容。
关于java - 无法让正则表达式在 Java 中匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909321/