Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python';什么是regex?_Python_Regex - Fatal编程技术网

如何在Python';什么是regex?

如何在Python';什么是regex?,python,regex,Python,Regex,我有一个字符串,我想在开头和结尾用一个搜索模式匹配一些内容。如何做到这一点 假设我们有一个字符串,如: string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg" 我想这样做: re.search("^ftp:// & .jpg$" ,string) 显然,这是不正确的,但我希望它能让我的观点得到理解。这可能吗?完全不使用正则表达式怎么样 如果string.startswith(“ftp://”)和string.en

我有一个字符串,我想在开头和结尾用一个搜索模式匹配一些内容。如何做到这一点

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

 string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
我想这样做:

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

显然,这是不正确的,但我希望它能让我的观点得到理解。这可能吗?

完全不使用正则表达式怎么样

如果string.startswith(“ftp://”)和string.endswith(“.jpg”):
你不觉得这读起来更好吗

您还可以支持“开始”和“结束”的多个选项:

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

如果需要正则表达式搜索。请注意,您必须转义句点,因为它在正则表达式中有特殊含义。

不要转义,请使用
^ftp://(.*?)\。与
重新搜索相比,jpg$
将:

re.match(r'(ftp|http)://.*\.(jpg|png)$', s)
这里需要注意两件事:

  • r'
    用于字符串文本,使正则表达式中的反斜杠变得简单
  • string
    是一个标准模块,所以我选择了
    s
    作为变量
  • 如果多次使用正则表达式,则可以使用来构建一次状态机,然后使用
    r.match(s)
    来匹配字符串
如果需要,还可以使用模块为您解析URL(尽管您仍然需要提取扩展名):


我想提取所有数字,包括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)])

参考文献:

我会的,但它更复杂,因为有许多有效的开始和结束序列。如果我知道如何处理这个简单的案例,我就能使它在更复杂的现实中工作@谷歌:你也可以查询多个字符串,见我的更新。
>>> 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
import re

s = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
print(re.search("^ftp://.*\.jpg$", s).group(0))
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)])