【发布时间】:2012-04-14 09:05:02
【问题描述】:
我有一个字符串,我想在开头 和 以单个搜索模式匹配某些内容。如何才能做到这一点?
假设我们有一个像这样的字符串:
string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
我想做这样的事情:
re.search("^ftp:// & .jpg$" ,string)
显然,这是不正确的,但我希望它能够理解我的意思。这可能吗?
【问题讨论】:
我有一个字符串,我想在开头 和 以单个搜索模式匹配某些内容。如何才能做到这一点?
假设我们有一个像这样的字符串:
string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
我想做这样的事情:
re.search("^ftp:// & .jpg$" ,string)
显然,这是不正确的,但我希望它能够理解我的意思。这可能吗?
【问题讨论】:
不使用正则表达式怎么样?
if string.startswith("ftp://") and string.endswith(".jpg"):
你不觉得这样更好看吗?
您还可以支持多个开始和结束选项:
if (string.startswith(("ftp://", "http://")) and
string.endswith((".jpg", ".png"))):
【讨论】:
re.match 将 match the string at the beginning,与 re.search 形成对比:
re.match(r'(ftp|http)://.*\.(jpg|png)$', s)
这里需要注意两点:
r'' 用于字符串文字,以便在正则表达式中使用反斜杠string 是标准模块,所以我选择了s 作为变量r = re.compile(...) 构建一次状态机,然后使用r.match(s) 匹配字符串如果您愿意,也可以使用urlparse 模块为您解析网址(尽管您仍然需要提取扩展名):
>>> 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
【讨论】:
不要greedy,使用^ftp://(.*?)\.jpg$
【讨论】:
试试
re.search(r'^ftp://.*\.jpg$' ,string)
如果你想要一个正则表达式搜索。请注意,您必须将句点转义,因为它在正则表达式中具有特殊含义。
【讨论】:
import re
s = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
print(re.search("^ftp://.*\.jpg$", s).group(0))
【讨论】:
我想提取所有数字,包括 int 和 float。
它对我有用。
import re
s = '[11-09 22:55:41] [INFO ] [ 4560] source_loss: 0.717, target_loss: 1.279,
transfer_loss: 0.001, total_loss: 0.718'
print([float(s) if '.' in s else int(s) for s in re.findall(r'-?\d+\.?\d*', s)])
参考:https://www.tutorialspoint.com/How-to-extract-numbers-from-a-string-in-Python
【讨论】: