2

I am trying to process text and replace all the occurence that start with "www." with a certain word (in this cases "Banana"), but I want to exclude all the cases in which there is "http://" before the "www".

When I use a positive lookahead it works (only the http://www case changes), but when I use a negative lookahead - both words change.

Can you help me with this one?

String baseString = "replace this: www.q.com and not this:http://www.q.com";
String positiveLookahead = baseString.replaceAll("(?:http://)www([^ \n\t]*)", "Banana");
String negativeLookahead = baseString.replaceAll("(?!http://)www([^ \n\t]*)", "Banana");

//positiveLookahead works (changes only the scond phrase), but positiveLookahead does not (changes both)
2
  • Shouldn't you be looking behind, not ahead? Commented Aug 23, 2018 at 10:55
  • @khelwood You are right, see Wiktor response. Thanks! Commented Aug 23, 2018 at 11:17

1 Answer 1

2

Use a negative lookbehind, (?<!http://):

String negativeLookahead = baseString.replaceAll("(?<!http://)www[^ \n\t]*", "Banana");

The (?<!http://)www[^ \n\t]* pattern matches:

  • (?<!http://) - a location in the string that is not immediately preceded with http://
  • www - a literal www substring
  • [^ \n\t]* - any 0+ chars other than space, newline and carriage return (probably you want to try \\S* instead).
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, that's working :) So what does lookahead do?
@TalSheffer A negative lookahead matches a location in the string that is not immediately followed with a pattern, so (?!a)b is always equal to b as b is not an a.
Got it. So what would be a legit use for a negative lookahead?
@TalSheffer Plenty. For example, see this today's answer of mine. More on negative lookahead here, and here.
Thank you very much! Much appriciated!

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.