Reputation: 191
I would like some help in building a regular expression. The conditions are as follows
#
-
-apples
or -bananas
Some test cases
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
Reputation: 103884
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)$/
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)$
Upvotes: 1