0

I have the following string:

"GET /phpmyadmin HTTP/1.1"

I want the regex in Python which can separate GET, phpmyadmin, HTTP and 1.1 like method, localhost, protocol and version.

Daniel
  • 2,355
  • 9
  • 23
  • 30
Payal
  • 55
  • 2
  • 9
  • 2
    have you tried anything yet? any piece of code? – Saqib Shahzad Nov 17 '18 at 09:15
  • Possible duplicate of [Split a string by spaces -- preserving quoted substrings -- in Python](https://stackoverflow.com/questions/79968/split-a-string-by-spaces-preserving-quoted-substrings-in-python) – Moh Mah Nov 17 '18 at 15:19

3 Answers3

0

You don't need a regex for this. Split your string based on the delimiter and extract items to assign to required variables:

s = "GET /phpmyadmin HTTP/1.1"

method, [localhost, protocol], version = [(x.strip(), y.split(), z) for x, y, z in [s.split('/')]][0]


More readable way:
for x, y, z in [s.split('/')]:
    method = x.strip()
    localhost, protocol = y.split()
    version = z
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Something like this should work fine, so long as the structure is always the same.

s = "GET /phpmyadmin HTTP/1.1"
matches = re.match( r'(.*) (.*) (.*)/(.*)', s, re.M|re.I)
ans = list(matches.groups())

Reading over regexes would probably be helpful: https://www.tutorialspoint.com/python/python_reg_expressions.htm.

Edit: I agree with above, you don't need a regex, but it is prettier than the splits and list comprehensions.

stoksc
  • 324
  • 3
  • 12
0

Doing it with regex, you can split it with [ /]+

Python code for same would be,

import re
s = 'GET /phpmyadmin HTTP/1.1'
tokens = re.split('[ /]+',s)
print(tokens)

This gives following output,

['GET', 'phpmyadmin', 'HTTP', '1.1']
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36