2

I have the following regex which I use to find a word:

(?<=\s)([\w\@\-]+)(?=\s)

I want to further modify this regex to exclude a list of words e.g. do not match if the word is 'cat' or 'dog'.

How do I accomodate the regex to achieve this?

hakre
  • 193,403
  • 52
  • 435
  • 836
ObiHill
  • 11,448
  • 20
  • 86
  • 135
  • This one is similar: [I have a PHP regEx, how do add a condition for the number of characters?](http://stackoverflow.com/q/13994553/367456), even specifying a minimum length what qualifies a word. – hakre Dec 29 '12 at 16:04
  • @hakre It doesn't seem that similar to me?! – ObiHill Dec 29 '12 at 16:07
  • Oh it is, the answer you accepted uses the same regex features. ;) - It just does the length check as well, which you don't have here (well you have one or more characters to form a word). – hakre Dec 29 '12 at 16:08
  • @hakre Ok, but the answer to that doesn't answer my question. You'll have to be a Regex ninja to draw the correlation between the two, and a regex ninja am I not, ergo my question. – ObiHill Dec 29 '12 at 16:37
  • I wrote similar, not identical. It's just a link in case someone stumbles over this question and is looking for alternatives. It's not saying that your question would be wrong or anything. – hakre Dec 29 '12 at 16:56

1 Answers1

7
\b(?!(?:dog|cat)\b)([\w@-]+)\b

Here if you want to match word start/end with @

(?<=\s)(?!(?:dog|cat)(?=\s))([\w\@\-]+)(?=\s)
hakre
  • 193,403
  • 52
  • 435
  • 836
slier
  • 6,511
  • 6
  • 36
  • 55
  • +1, but not equivalent to @ChuckUgwuh's regex - it won't match an entire "word" if it ends in `@` or `-` (unlikely), and it *will* match at the start/end of the string (where his solution won't). – Tim Pietzcker Dec 29 '12 at 15:57
  • @TimPietzcker yeah u right..he can change \b to lookaround assertion to match @ at the start/end of string – slier Dec 29 '12 at 16:02
  • @slier Thanks. The lookaround assertion for @, how would I pull that off?! – ObiHill Dec 29 '12 at 16:06