简体   繁体   中英

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

But when I then paste it into java and escape all of the back- slashes and call 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.

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**");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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