开发者

Java Regex: replacing a specific kind of url in a string?

开发者 https://www.devze.com 2023-03-29 11:11 出处:网络
Sample input: \"http://bits.wikimedia.org/w/extensions-1.17/MobileFrontend/stylesheets/webkit.css\" my attempt: \"http://.*?/stylesheets/webkit.css\" does not find any matches

Sample input:

"http://bits.wikimedia.org/w/extensions-1.17/MobileFrontend/stylesheets/webkit.css"

my attempt: "http://.*?/stylesheets/webkit.css" does not find any matches

The part of the url between "http://"开发者_如何学运维 and "webkit.css" is variable

Thanks!

My bad, I was using Java's replace() function as opposed to replaceFirst() or replaceAll()


One solution using groups:

String input = "http://bits.wikimedia.org/w/extensions-1.17/" + 
               "MobileFrontend/stylesheets/webkit.css";

String replacement = "example.com";

String result = input.replaceAll("(http://).*?(/stylesheets/webkit\\.css)",
                "$1" + replacement + "$2");

Result will equal http://example.com/stylesheets/webkit.css.


Another option using look arounds:

String result = input.replaceAll("(?<=http://).*(?=/stylesheets/webkit\\.css)",
                                 replacement);

which says "replace everything in between http:// and /stylesheets/webkit.css with replacement.

0

精彩评论

暂无评论...
验证码 换一张
取 消