问题
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