Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for URL with query string

I'm trying to create a regular expression to use as a rule in fiddler. I'm not very good at regular expressions.

This regular expression:

http://myServer:28020/MyService/ItemWebService.json?([a-zA-Z]+)

Matches the URL below:

http://myServer:28020/MyService/ItemWebService.json?action=keywordSearch&username=StockOnHandPortlet&sessionId=2H7Rr9kCWPgIZfrxQiDHKp0&keywords=blue&itemStatus=A

So far so good. But why when I try this regular expression:

http://myServer:28020/MyService/ItemWebService.json?action=keywordSearch([a-zA-Z]+)

It does not match the above URL. Why would that be?

like image 590
Richie Avatar asked Dec 24 '22 17:12

Richie


1 Answers

In a regular expression, you need to escape . and ? outside of character class.

So, this is enough to match the URL itself:

http://myServer:28020/MyService/ItemWebService\.json

URL with query string can be matched with

http://myServer:28020/MyService/ItemWebService\.json\??(?:&?[^=&]*=[^=&]*)*

See demo

Explanation:

  • http://myServer:28020/MyService/ItemWebService\.json - matches the base URL where we need to escape . to match it literally
  • \?? - matches 0 or 1 (due to ? quantifier) literal ?
  • (?:&?[^=&]*=[^=&]*)* - matches 0 or more (due to *) sequences of &?[^=&]*=[^=&]*:
    • &? - 0 or 1 & (no need escaping)
    • [^=&]* - 0 or more characters other than = and &
    • = - n equals sign
    • [^=&]* - 0 or more characters other than = and &

If you want to match a URL that has the first query parameter=value set to action=keywordSearch, you can use the following regex:

http://myServer:28020/MyService/ItemWebService\.json\?action=keywordSearch(?:&?[^=&]*=[^=&]*)*
like image 129
Wiktor Stribiżew Avatar answered Jan 09 '23 03:01

Wiktor Stribiżew