2

Here Is My Regex Code:

/fun(niest|!ny$)?/ig

How would I get the word "fun" or "funniest" but not the word "funny" through regex, here is what I have. Is there any way of doing this, if so please help!

1
  • 1
    Try it like this /fun(?!ny)(niest)?/ Commented Apr 22, 2016 at 20:45

1 Answer 1

1

You can use word boundaries \b and an optional group (?:niest)?:

/\bfun(?:niest)?\b/ig

See the regex demo

The pattern matches:

  • \b - leading word boundary
  • fun - literal character sequence fun
  • (?:niest)? - an optional (one or zero occurrences) niest literal character sequence (not captured into any group since the group is non-capturing, i.e. used only for grouping)
  • \b - trailing word boundary.

Your fun(niest|!ny$)? matches fun, or funniest or fun!ny that is at the end of the string.

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

6 Comments

how would this be done with multiple options in the regex which are separated with the |, not as an option phrase/letter but as a word like funny the honey e.g: funny|honey
funny|honey will match either funny or honey. Could you be more precise?
You thought that to match a whole word you need to include a "negative alternative"? That is possible in PHP (PCRE), not in JS. Either use \b (as I showed) or non-ambiguous /(^|\W)(fun(?:niest)?)(?=\W|$)/ig (but then you will need to use backreferences wisely if replacing, or do more post-processing if matching).
Another option: (funniest|fun(?!ny))
@TimothyKanski: If you insist, then again, it should be /\b(funniest|fun(?!ny\b)\w*)\b/ig - otherwise I see no use for the lookahead. The thing is, the words are to be matched as whole words in the current scenario, and the 2 words are to be matched only. If OP says any word having or starting with fun should be matched, but not funny, then the lookahead solution will be the best.
|

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.