Regex for URL with query string

喜欢而已 提交于 2021-02-04 18:50:06

问题


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?


回答1:


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(?:&?[^=&]*=[^=&]*)*



回答2:


Use

(\?|\&)([^=]+)\=([^&]+)

With g option (global)

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


来源:https://stackoverflow.com/questions/31367267/regex-for-url-with-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!