office.aizaz
office.aizaz

Reputation: 191

Building regular expression ending with either one word or other

I would like some help in building a regular expression. The conditions are as follows

Some test cases

  1. #hshg1h2-hd212df-7632jhsd-bananas (Match)
  2. #jhkj31j-jkh213j-jjkhjj324-apples (Match)
  3. hjsdjjhsd-jhsshdjs-jdshdsj-apples (No Match)
  4. #---apples (No Match)
  5. #jhkj31j-jkh213j-jjkhjj324 (No Match)
  6. #jhkj31j-jkh213j-jjkhjj324-apples-bananas (No Match)

I created the following expression ^#([a-zA-Z0-9]{1,}-){1,}(apples|bananas)$. For most of the test cases, it provides the correct result. However it also matches the test case 6 which it should not.

Background

The test cases simulate product-ids for the two products apples and bananas. Those ids always contains as the last group -bananas or -apples. Thus -apples-bananas or vice versa is suppose be invalid product id.

Could anyone please show me how can I do this?

Upvotes: 0

Views: 69

Answers (1)

dawg
dawg

Reputation: 103884

You can use lookaheads and alteration:

/^#(?!.*apples.*bananas|.*bananas.*apples)(?=[a-zA-Z0-9]+-[a-zA-Z0-9]+).*(?:apples|bananas)$/

Demo

And it is always good to use word boundary assertions:

/^#(?!.*\bapples\b.*\bbananas\b|.*\bbananas\b.*\bapples\b)(?=[a-zA-Z0-9]+-[a-zA-Z0-9]+).*(?:\bapples\b|\bbananas\b)$/

Alternatively, here is a modified version of the regex in comments (that is pretty good!)

^#(?:(?!\b(?:apples|bananas)\b)[a-zA-Z0-9]+-)+\b(?:apples|bananas)$

Demo

Upvotes: 1

Related Questions