How do I make an query parameter optional in regex?

Viewed 31

i have this regex:

^https?:path\?id=([a-zA-Z0-9._]+)&?.*&gl=([^&|\n|\t\s]+)&?.*$

the query parameter:

?id=([a-zA-Z0-9._]+)&?.*&gl=([^&|\n|\t\s]+)&?.*$

how do i make "gl" to be optional?

1 Answers

You can use

^https?:path\?id=([^&]+)(?:.*?(?:&gl=([^&\s]+).*)?)?$

See the regex demo.

Details:

  • ^ - start of string
  • http - a fixed http string
  • s? - an optional s char
  • :path\?id= - a fixed :path?id= string
  • ([^&]+) - Group 1: one or more chars other than a & char
  • (?:.*?(?:&gl=([^&\s]+).*)?)? - an optional sequence of
    • .*? - any zero or more chars other than line break chars as few as possible
    • (?:&gl=([^&\s]+).*)? - an optional sequence of
      • &gl= - a fixed string
      • ([^&\s]+) - Group 2: one or more chars other than whitespace and &
      • .* - any zero or more chars other than line break chars as many as possible
  • $ - end of string.
Related