正则表达式匹配/替换

时间:2012-05-07 22:05:37

标签: javascript python regex

python中这个(Javascript)的等价物是什么?

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

我是Python的新手,还不太了解正则表达式系统:(

2 个答案:

答案 0 :(得分:1)

你已经得到了它

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

答案 1 :(得分:1)

Python中代码的粗略等价物是

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)