user3451476 user3451476 - 4 months ago 31
Java Question

Regex matching in python 2.7

I am new to Python and would like to know how to have build a regex pattern to match a URL

I have the following code in Java and it works. I need to have a similar one in python

Java:

URI uri = new URI("http://localhost:8080")

Matcher m = Pattern.compile("(.*)" + "/client" + "/([0-9]+)")
.matcher(uri.getPath());


Could someone guide me with having an equivalent regex in Python

Answer

Here's the equivalent in Python 2.7:

import re
from urlparse import urlparse

url = urlparse('http://localhost:8080')

match = re.match(r'(.*)/client/([0-9]+)', url.path)

EDIT

Here's how you would use match to get the individual components (just guessing as to what you want to do next):

if match:
    prefix = match.group(1)
    client_id = int(match.group(2))