为什么java不能识别这个正则表达式?

时间:2013-10-27 14:32:39

标签: java regex

我写了这个正则表达式:

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

此正则表达式应找到字符串中的每个图像链接

如你点击下面的链接,你可以看到它的工作正常。

http://rubular.com/r/FYwP8Aprdb

但是当我将其粘贴到java中并转义所有反斜杠并调用replaceAll(regex,string);

程序找不到任何东西?

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

上面的代码应该获取字符串中的每个图像,然后将其封装在 $ 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

 */

}

我的假设是我错误地逃脱了正则表达式,但我不确定。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

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

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