简体   繁体   English

为什么Java无法识别此正则表达式?

[英]Why can't java recognize this Regular Expression?

I wrote this Regular Expression: 我写了这个正则表达式:

((http):\\/\\/\\S*\\.(jpg|gif|png))

This Regex should find every image link in a string 这个正则表达式应该找到字符串中的每个图像链接

And as you can see it work fine if you click the link below. 如您所见,如果您单击下面的链接,它可以正常工作。

http://rubular.com/r/FYwP8Aprdb http://rubular.com/r/FYwP8Aprdb

But when I then paste it into java and escape all of the back- slashes and call replaceAll(regex, string); 但是当我然后将其粘贴到Java中并转义所有反斜杠并调用replaceAll(regex,string);

The program can't find anything? 该程序找不到任何东西?

String regex = "((http):\\/\\/\\S*\\.(jpg|gif|png))";
boxText.replaceAll(regex, "**$0**");

The code above should get every image in a string and then capsulate it in $0 But upon running the program and testing, nothing happens. 上面的代码应该将每个图像都存储在一个字符串中,然后将其封装在$ 0中。但是在运行程序和测试后,什么也没有发生。

public class SSCCE {

public static void main(String[] args) {

    String boxText = "http://www.desibucket.com/db2/01/26039/26039.jpg";

    String regex = "((http):\\/\\/\\S*\\.(jpg|gif|png))";
    boxText.replaceAll(regex, "**$1**");        

    System.out.println(boxText);
}

/* output

  http://www.desibucket.com/db2/01/26039/26039.jpg

 */

}

My assumption is that I've escaped the regex incorrectly, but I'm not sure. 我的假设是我错误地逃避了正则表达式,但是我不确定。 Any ideas? 有任何想法吗?

字符串是不可变的 :表达式匹配,但永远不会将值重新分配给replaceAll的结果

boxText = boxText.replaceAll(regex, "**$1**");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM