Home > Enterprise >  Building regular expression ending with either one word or other
Building regular expression ending with either one word or other

Time:01-23

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

  • The expression must start with #
  • Then it should contain atleast one or more groups of alphanumeric characters separated by -
  • Each group contains atleast one alphanumeric character
  • The expression should end either with -apples or -bananas

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?

CodePudding user response:

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)$/
  •  Tags:  
  • Related