2

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()

3
  • Are you escaping your periods appropriately? And how are you trying to replace a String or Strings here? Can you show more code? Commented Aug 21, 2011 at 19:19
  • 1
    What code are you using? Your regex is really simple and should work. @Hovercraft Full Of Eels, even if he doesn't, it should match anyway (though it would indeed be better to escape them) Commented Aug 21, 2011 at 19:21
  • @Vache: yup, you're right, as I've just tested them. Commented Aug 21, 2011 at 19:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.