Home > OS >  Multiple matching groups regex
Multiple matching groups regex

Time:02-02

I thought that surrounding expressions with brackets allowed you to do multiple matches.

/(^(.*?)\?).(([?&])([^=] )=([^&] ))/g

The above regex should first match everything before ?, then the second one should match all of the URL Parameters.

search.php?make=8&vehicle_type=car&location_path=used&sort=nis&p=

Both work perfect alone, but not together, I get no matches.

CodePudding user response:

There are no matches, as this part of the pattern \?).(([?&]) expects to match 3 characters: ?, any character due to the dot, and either ? or &

If you want 2 separate groups, 1 for the url, and the second one with all the parameters, you can match the first key/value pair and optionally repeat more key/value pairs.

^([^?&]*)[?&]([^=] =[^&]*(?:&[^=] =[^&]*)*)$
  • ^ Start of string
  • ([^?&]*) Capture group 1, match any character except ? and &
  • [?&] Match either ? or &
  • ( Capture group 2
    • [^=] =[^&]* Match a key/value pair, exluding the = before and excluding the & after
    • (?:&[^=] =[^&]*)* Optionally repeat the previous pattern with a leading &
  • ) Close capture group 2
  • $ End of string

Regex demo

CodePudding user response:

I understand the question 2 different ways

Match 2 groups: the url the parameters string

(^([^?]*)|([^?]*)$)

Will match:

  • search.php
  • make=8&vehicle_type=car&location_path=used&sort=nis&p=

This works because we look for a string of any non-? character until the first is found, OR ("|") a string of non-? characters that go to the end of the test string.

https://regex101.com/r/uD5SGG/1

Match multiple groups: the url one group per parameter

(^([^?]*)|([\w_]*=[\w_]*))

Will match:

  • search.php
  • make=8
  • vehicle_type=car
  • location_path=used
  • sort=nis
  • p=

Note that the & do not match. Again, we use | as in "OR". [\w_]* indicates that we look for parameters composed of letters or "_".

https://regex101.com/r/2VL6i0/1

  •  Tags:  
  • Related