[英]How to find all the exact matches in a given string using python Regex
[英]How do I print matches from a regex given a string value in Python?
我在python中有一个字符串“/browse/advanced-computer-science-modules?title=machine-learning”。我想打印第二个“/”和“?”之间的字符串,即“advanced-computer -科学模块”。 我创建了一个正则表达式,如下所示 ^([az] [-] [az])*?$ 但是当我从 re 模块运行 the.findall() function 时它不打印任何内容。 有什么办法可以解决这个问题吗?
我创建了自己的正则表达式并在 python 中导入了 re 模块。下面是我的代码片段,没有返回任何内容。
regex = re.compile(r'^([a-z]*[\-]*[a-z])*?$')
str = '/browse/advanced-computer-science-modules?title=machine-learning'
print(regex.findall(str))
由于这似乎是 URL,我建议您改为使用URL 解析工具:
>>> from urllib.parse import urlsplit
>>> url = '/browse/advanced-computer-science-modules?title=machine-learning'
>>> s = urlsplit(url)
SplitResult(scheme='', netloc='', path='/browse/advanced-computer-science-modules', query='title=machine-learning', fragment='')
>>> s.path
'/browse/advanced-computer-science-modules'
>>> s.path.split('/')[-1]
'advanced-computer-science-modules'
正则表达式如下:
\/[a-zA-Z\-]+\?
然后你抓住了 substring:
regex.findall(str)[1:len(str) - 1]
非常具体到这个问题,但它应该工作。
或者,您可以使用string
的split
方法:
str = '/browse/advanced-computer-science-modules?title=machine-learning'
result = str.split('/')[-1].split('?')[0]
print(result)
#advanced-computer-science-modules
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.