Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re.search Q
#11
(Nov-30-2021, 06:15 PM)Gribouillis Wrote: I suggest this ersatz
>>> {m.group(1): m.group(2) for m in re.finditer(r'([a-z]+)\=([^=&\n]*)', request)}
{'q': '0.9\r', 'ssid': 'my_ssid', 'password': 'my_pass', 'token': '', 'ip': '192.168.1.222', 'gw': '192.168.1.1', 'sbnet': '255.255.255.0', 'dns': '8.8.8.8'}
Thanks but I cannot use this syntax as I'm using Micropython. Anyhow, I need to list the groups as in my prior post.
Reply
#12
(Nov-30-2021, 06:21 PM)ebolisa Wrote:
(Nov-30-2021, 06:15 PM)Gribouillis Wrote: I suggest this ersatz
>>> {m.group(1): m.group(2) for m in re.finditer(r'([a-z]+)\=([^=&\n]*)', request)}
{'q': '0.9\r', 'ssid': 'my_ssid', 'password': 'my_pass', 'token': '', 'ip': '192.168.1.222', 'gw': '192.168.1.1', 'sbnet': '255.255.255.0', 'dns': '8.8.8.8'}
Thanks but I cannot use this syntax as I'm using Micropython. Anyhow, I need to list the groups as in my prior post.

Then you have to prevent the capture group from matching beyond the field by excluding '&'.

import re
request = 'POST /configure HTTP/1.1\r\nHost: 192.168.4.1\r\nOrigin: http://192.168.4.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 15_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Mobile/15E148 Safari/604.1\r\nReferer: http://192.168.4.1/\r\nContent-Length: 108\r\nAccept-Language: en-GB,en;q=0.9\r\n\r\nssid=my_ssid&password=my_pass&token=&ip=192.168.1.222&gw=192.168.1.1&sbnet=255.255.255.0&dns=8.8.8.8'

fields = ["ssid", "password", "token", "ip", "gw", "sbnet", "dns"]
regex = "\&.*".join(f"{x}=([^&]*)" for x in fields)

match = re.search(regex, request)
print(match.group(1))
print(match.group(2))
print(match.group(3))
print(match.group(4))
Output:
my_ssid my_pass 192.168.1.222
ebolisa likes this post
Reply
#13
Thank you all. Actually the code shown in my first post is correct, there's an error in the string received from the URL which had the variables in the wrong order. So, once fixed that, the code works fine.

import re

request = '...q=0.9\r\n\r\nssid=my_ssid&password=my_pass&token=abcdef&ip=192.168.1.222&sbnet=255.255.255.0&gw=192.168.1.1&dns=8.8.8.8'
match = re.search("ssid=([^&]*)&password=(.*)&token=(.*)&ip=(.*)&sbnet=(.*)&gw=(.*)&dns=(.*)", request)

for _ in range(1, 8):
    print(match.group(_)) 
Output:
my_ssid my_pass abcdef 192.168.1.222 255.255.255.0 192.168.1.1 8.8.8.8
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020