1

I need a REGEX to match the following 3 input strings:

serviceType=SALE&propertyType=HOUSE&city=1
propertyType=HOUSE&serviceType=SALE&city=1
city=1&propertyType=HOUSE&serviceType=SALE
city=1&serviceType=SALE&propertyType=HOUSE
serviceType=SALE&propertyType=HOUSE
serviceType=SALE

and not match

serviceType=SALE&propertyType=HOUSE&city=2
propertyType=HOUSE&city=2&serviceType=SALE
city=2&propertyType=HOUSE&serviceType=SALE
serviceType=SALE&propertyType=FARM&city=1
serviceType=SALE&propertyType=UNIT
serviceType=RENTAL&propertyType=HOUSE
serviceType=RENTAL

I tried the following which matches the first input string but couldn't figure out the rest:

(?=.*serviceType=SALE)(?=.*propertyType=HOUSE)(?=.*city=1)
zoro74
  • 171
  • 15

1 Answers1

2

It seems you are looking for something like this:

^serviceType=SALE(?:&propertyType=HOUSE(?:&city=1)?)?$

See here for a demo

EDIT

If the order of parameters is not important, then use this regex:

^(?:(?:&|^)(?:serviceType=SALE|propertyType=HOUSE|city=1)){1,3}$

It means "a & or start of the string (^), which is followed by any of the three parameters, all repeated 1 to 3 times.

See new demo.

If you are searching this pattern within an URL, I guess you should replace the initial ^ with (?:^|(?<=\?)) for stating that the string can also be preceded by a question mark.

logi-kal
  • 7,107
  • 6
  • 31
  • 43
  • hi @horcrux, the above regex doesn't work in MySQL unfortunately. The error I am getting is "Got error 'repetition-operator operand invalid' from regexp". The reason is explained in details [here](https://stackoverflow.com/questions/18317183/1139-got-error-repetition-operator-operand-invalid-from-regexp). Could you please help? – zoro74 Apr 15 '19 at 12:58
  • There is no lazy operator in the above regex. I guess you just have to remove `?:` – logi-kal Apr 16 '19 at 07:11
  • thanks @horcrux, I've checked the pattern to select query from search s where s.query regexp '^((&|^)(serviceType=SALE|propertyType=HOUSE|city=1)){1,3}$' which still works in the regex tester but returns no matches in MySQL. Do you see anything wrong with it? – zoro74 Apr 16 '19 at 12:16
  • I don't see any error. Are you sure the input is like `serviceType=SALE&propertyType=HOUSE&city=1` or it is a full url? Be aware this regex won't work if there are other characters near the string. – logi-kal Apr 16 '19 at 15:24
  • all good, it was my bad.. I copy/paste the code directly to the table field instead of running insert statement. All good and working fine. Thanks again @horcrux – zoro74 Apr 17 '19 at 10:57