1

I have this string:

goose goose goose random goose goose test goose goose goose

I'm using regular expression in TextMate to find any word that isn't goose. therefore random and test.

So I tried this regular expression:

[^\sgoose\s]

But this isn't quite doing what I want. It's matching any character that isn't a space or letters g o s e.

How can I find get the regular expression to match any whole word that isn't goose? Therefore, there should be 2 matches random and test.

| |
4

Not sure it will work with TextMate (I do not have it, but I've tested with Notepad++).

You could try:

\b(?:(?!goose)\w)+\b

Explanation:

\b          : word boundary
(?:         : start non capture group
  (?!goose) : negative lookahead, make sure we don't have the word "goose"
  \w        : a word character, you may use "[a-zA-Z]" for letters only or "." for any character but newline
)+          : group may appears 1 or more times
\b          : word boundary
| |
1

I find mistake in this expression, you can check it here: https://regex101.com/r/XQhqAB/1

As you see, the previous expression \b(?:(?!goose)\w)+\b doesn't find: gooses1, goose1 and all the words that start from the goose prefix. Obviously these are other words...

Correct expression (for extended words): (?<=^|\s)(?!goose(?:\s|$))\S+(?=\s|$)
You test it here: https://regex101.com/r/XQhqAB/4

Correct expression (for simple words): \b(?!goose\b)\w+\b
Test it: https://regex101.com/r/XQhqAB/5

Sincerely.

| |
  • 1
    (1) OK, good job; your expression finds words that begin with “goose”; for example, “gooseberry” and “goosepimple”.  (2) Your regex also matches words that end with “goose”; for example, “mongoose” and “wildgoose”. But shame on you for not noticing that the other answer fails on those, too.  (3) The OP accepted Toto’s answer, which uses \b, suggesting that that met their needs. So why did you replace it with \s alternations? Your answer does not catch non-goose words if they are adjacent to punctuation. – G-Man Says 'Reinstate Monica' Nov 25 '19 at 23:43
  • Thank you, and I think you're right. The expression can be simplified and optimized: \b(?!goose\b)\w+\b. – Oleg Konev Nov 26 '19 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.