如何匹配Python正则表达式中的开始和结束?

2024-04-28 14:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我想用一个单一的搜索模式来匹配开头和结尾的内容。怎么能做到?

假设我们有一个字符串,比如:

 string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"

我想这样做:

 re.search("^ftp:// & .jpg$" ,string)

显然,这是不正确的,但我希望它能让我明白我的观点。这可能吗?


Tags: the字符串imagerecom内容stringwww
3条回答

不要是greedy,使用^ftp://(.*?)\.jpg$

不使用正则表达式怎么样?

if string.startswith("ftp://") and string.endswith(".jpg"):

你不觉得这样读起来更好吗?

您还可以支持多种开始和结束选项:

if (string.startswith(("ftp://", "http://")) and 
    string.endswith((".jpg", ".png"))):

^{}match the string at the beginning,与re.search相反:

re.match(r'(ftp|http)://.*\.(jpg|png)$', s)

这里要注意两件事:

  • r''用于字符串文本,使在regex中使用反斜杠变得简单
  • string是一个标准模块,所以我选择了s作为变量
  • 如果多次使用regex,可以使用^{}来构建状态机,然后使用r.match(s)来匹配字符串

如果需要,还可以使用^{}模块为您解析URL(尽管您仍然需要提取扩展名):

>>> allowed_schemes = ('http', 'ftp')
>>> allowed_exts = ('png', 'jpg')
>>> from urlparse import urlparse
>>> url = urlparse("ftp://www.somewhere.com/over/the/rainbow/image.jpg")
>>> url.scheme in allowed_schemes
True
>>> url.path.rsplit('.', 1)[1] in allowed_exts
True

相关问题 更多 >