regexlogical-operators

RegEx match multiple string conditions in AND operator


I need to match the following rules in long string:

 - key1=.*(a1|a2).* OR key2=.*(b1|b2|b3).* OR key3=.*(c1|c2|c3).*
 - AND key1=.*(d1|d2|d3|d4).*

the '=' is intended as 'contains any of'

I've tried the following regex on regex101.com, but is not working as expected:

.*((key1=(?=.*(a1|a2)))|(key2=(?=.*(b1|b2|b3)))|(key3=(?=.*(c1|c2|c3))))&(key1=(?=.*(d1|d2|d3|d4))).*

some string that should match:

key1=a2,d3
key2=b1,b3key1=d1
key2=b2key3=c3,a2key1=d4
key1=d2abckey2=b2,b3key1=a1

some string that should NOT match:

key1=d2
key1=a1key2=b1
key2=b2key3=a1

what is wrong with my regex expression? what do you think? many thank


Solution

  • You can use a single positive lookahead to make sure that key1 is present with at least an occurrence of d and a digit 1-4.

    Then you can use another lookahead to assert one of key 1, key2 or key3 with the allowed digits.

    Note that you can shorten the alternations | for (a1|a2) to a character class a[12]

    ^(?=.*key1=[a-z0-9,]*d[1-4])(?=.*(?:key1=a[12]|key2=b[123]|key3=c[123])).+
    

    Regex demo

    The pattern matches: