使用正则表达式

时间:2016-07-01 13:30:57

标签: python regex

url="www.example.com/thedubaimall"

我想保存com/之后的所有内容,我只需要thedubaimall

我如何使用正则表达式?

2 个答案:

答案 0 :(得分:4)

强制性的“如果你没有使用正则表达式怎么办?”回答:

>>> url="www.example.com/thedubaimall"
>>> url.partition(".com/")[2]
'thedubaimall'

答案 1 :(得分:2)

如果您想使用正则表达式,请使用re.findall

re.findall('(?<=com/).*$', "www.example.com/thedubaimall")
# ['thedubaimall']

使用@ DeepSpace的建议进行一些速度测试:

%timeit re.findall('(?<=com/).*$', "www.example.com/thedubaimall")
# The slowest run took 7.57 times longer than the fastest. This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 1.29 µs per loop

%timeit re.findall('com/(.*)', "www.example.com/thedubaimall")
# The slowest run took 6.48 times longer than the fastest. This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 992 ns per loop

%timeit "www.example.com/thedubaimall".partition(".com/")[2]
# The slowest run took 7.87 times longer than the fastest. This could mean that an intermediate result is being cached.
# 1000000 loops, best of 3: 204 ns per loop

看起来@ DeepSpace的建议有点快,@ Kevin的答案要快得多。