Pastor Bones
Pastor Bones

Reputation: 7351

Regular Expression Match/Replace

What would be the equivalent of this (Javascript) in python?

var patt = /sub(\d+)\.domain\.com\/(\d+)/
  , m    = url.match(patt)
  , url = 'http://sub' + m[1] + '.domain.com/' + m[2]

I'm new at Python and not quite understanding the regex system yet :(

Upvotes: 0

Views: 87

Answers (2)

Ansari
Ansari

Reputation: 8218

The rough equivalent of your code in Python would be

import re

url = 'http://sub36.domain.com/54'

patt = re.compile("sub(\d+)\.domain\.com\/(\d+)")
m = patt.search(url)
url = 'http://sub'+m.group(1)+'.domain.com/'+m.group(2)

Upvotes: 1

dfb
dfb

Reputation: 13289

You've pretty much already got it

>>> x = re.search("sub(\d+)\.domain\.com\/(\d+)","sub123.domain.com/546").groups()
('123', '546')
>>> url = "%s blah blah %s" % x

Upvotes: 1

Related Questions