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
-applesor-bananas
Some test cases
- #hshg1h2-hd212df-7632jhsd-bananas (Match)
- #jhkj31j-jkh213j-jjkhjj324-apples (Match)
- hjsdjjhsd-jhsshdjs-jdshdsj-apples (No Match)
- #---apples (No Match)
- #jhkj31j-jkh213j-jjkhjj324 (No Match)
- #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)$/
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)$/
