使用re模块在两个'/'之间获取数据

时间:2013-10-17 18:26:03

标签: python regex python-2.7

我需要从URL路径中提取一些文本,但我对Regex知之甚少。

import re

url = '/s/GETTHISDATA/canBeIgnored/canBeIgnored'
myData = #needs to equal GETTHISDATA

1 个答案:

答案 0 :(得分:2)

看看这个:

>>> import re
>>> url = '/s/GETTHISDATA/canBeIgnored/canBeIgnored'
>>> re.findall('(?<=/).*?(?=/)', url)
['s', 'GETTHISDATA', 'canBeIgnored']
>>> re.findall('(?<=/).*?(?=/)', url)[1]
'GETTHISDATA'
>>>

这样做可以捕获两个/之间的零个或多个字符(非贪婪)。更清楚的是,这是一个细分:

(?<=/) # Poisitive look-back assertion to test if text is preceded by a /
.*?    # Zero or more non-whitespace characters that are matched non-greedily
(?=/)  # Positive look-ahead assertion to test if text is followed by a /

然而,更简洁,非正则表达式的解决方案就是分开/

>>> url.split('/')
['', 's', 'GETTHISDATA', 'canBeIgnored', 'canBeIgnored']
>>> url.split('/')[2]
'GETTHISDATA'
>>>

就个人而言,我会使用第二种解决方案。正则表达式在这里似乎有些过分。

相关问题