Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse URL with a regex in Python

Tags:

python

regex

I want to get the query name and values to be displayed from a URL. For example, url='http://host:port_num/file/path/file1.html?query1=value1&query2=value2'

From this, parse the query names and its values and to print it.

like image 907
Myjab Avatar asked Jul 11 '26 13:07

Myjab


2 Answers

Don't use a regex! Use urlparse.

>>> import urlparse
>>> urlparse.parse_qs(urlparse.urlparse(url).query)
{'query2': ['value2'], 'query1': ['value1']}
like image 151
teukkam Avatar answered Jul 13 '26 08:07

teukkam


I agree that it's best not to use a regular expression and better to use urlparse, but here is my regular expression.

Classes like urlparse were developed specifically to handle all URLs efficiently and are much more reliable than a regular expression is, so make use of them if you can.

>>> x = 'http://www.example.com:8080/abcd/dir/file1.html?query1=value1&query2=value2'
>>> query_pattern='(query\d+)=(\w+)'
>>> # query_pattern='(\w+)=(\w+)'    a more general pattern
>>> re.findall(query_pattern, x)
[('query1', 'value1'), ('query2', 'value2')]
like image 23
jamylak Avatar answered Jul 13 '26 09:07

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!