noni noni - 1 month ago 7
Python Question

converting url to regex only username and password of the url

can someone please show me how convert only the username and the password of a link with regex ??

link = 'http://test.ddns.net:8000/get.php?username=9OsSVedOky&password=Oz2Vmx9GuW&type=list&output=tr'

url = 'http://test.ddns.net:8000/get.php?username=[a-zA-Z]|[0-9]|[$-@.&+]|&password=[a-zA-Z]|[0-9]|[$-@.&+]|&type=list&output=tr'

urls = re.findall(url, link)`

sorry if i'm not using the right terms but i'm new to coding .

thank you

Answer Source

Parsing a url with a regex is in general a bad idea, and especially bad when you have such a poor grasp of the syntax. If you must do it (and the only good reason is because you have been told to), then

>>> import re
>>> rx=re.compile(r"username=(?P<username>[^&]+).*password=(?P<password>[^&]+)")
>>> m = rx.search(link)
>>> m.groupdict()['username']
'9OsSVedOky'
>>> m.groupdict()['password']
'Oz2Vmx9GuW'

But I endorse Rawing's suggestion. It's much better:

>>> import urllib
>>> qsp=urllib.parse.parse_qs(link.partition('?')[2])
>>> qsp['username']
['9OsSVedOky']
>>> qsp['password']
['Oz2Vmx9GuW']