2

I want to find matches for string example but not www.example. What is the regex I can use? I've tried the following but it doesn't work:

(?!www.\)example

Ivar
  • 6,138
  • 12
  • 49
  • 61
Shivanand Sharma
  • 434
  • 3
  • 13

1 Answers1

9

If you just try to match a string that does start with example but not with www.example than it would be as easy as:

^example

Otherwise you can use a negative lookbehind:

(?<!\bwww\.)\bexample\b

The \b in here is a word boundery, meaning that it matches it, as long as it is not part of a string. (In other words if it isn't followed by or following any A-Za-z characters, a number or an underscore.)

As mentioned by @CasimiretHippolyte this does still match strings like www.othersubdomain.example.com.

Example

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • `(?<!www\.)example` So I tried everywhich way but I had no clue what `<` stands for. Would really appreciate what it does. I understand `^` is to match the begining and I left it out because I wanted to match in the middle of the paragraph as well. `()` is a capture group. `?!` is a negative lookahead? No clue about `<`. Thanks again. – Shivanand Sharma Sep 11 '17 at 19:12
  • @ShivanandSharma [This answer](https://stackoverflow.com/a/2973495/479156) goes in a bit deeper into the positive/negative lookahead/lookbehind if you want to get some good examples. – Ivar Sep 11 '17 at 19:16
  • This answer doesn't make sense. `^` and `(?<!www)` are zero-width assertions and checks the same position. You can't have the start of the string `^` and *not preceded by "www"* at the same time! `^example` produces exactly the same result, `(?<!www)` is useless (as an aside `(?<!www\.)` makes more sense but is useless too with the `^` anchor). `(?<!\bwww\.)example\b` is probably the right answer. – Casimir et Hippolyte Sep 11 '17 at 20:10
  • @CasimiretHippolyte You are right. I got thrown off by the `(?<!www)example` variant still matching the start of the string because I simply forgot the `\.`. Do you suggest I delete the answer or should I modify it to either `(?<!www\.)example` or your example? – Ivar Sep 11 '17 at 20:38
  • `(?<!www\.)example` is a more correct answer, but it doesn't match something like `abcwww.example.com` or `exampleabc.com`. That's why I suggested to add word boundaries. However `(?<!\bwww\.)\bexample\b` matches something like `www.othersubdomain.example.com`. It isn't so simple. – Casimir et Hippolyte Sep 11 '17 at 20:54
  • @CasimiretHippolyte I've updated by answer to make it at least a bit better. Thanks for pointing it out. – Ivar Sep 11 '17 at 21:12