Java Regex: replacing a specific kind of url in a string?
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
.
精彩评论