【问题标题】:How can I match the start and end in Python's regex?如何匹配 Python 正则表达式中的开始和结束?
【发布时间】:2012-04-14 09:05:02
【问题描述】:

我有一个字符串,我想在开头 以单个搜索模式匹配某些内容。如何才能做到这一点?

假设我们有一个像这样的字符串:

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

我想做这样的事情:

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

显然,这是不正确的,但我希望它能够理解我的意思。这可能吗?

【问题讨论】:

    标签: python regex


    【解决方案1】:

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

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

    你不觉得这样更好看吗?

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

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

    【讨论】:

    • 我会,但它更复杂,因为有许多有效的开始和结束序列。如果我知道如何做这个简单的案例,我可以让它在更复杂的现实中工作。 :)
    • @Google:你也可以查询多个字符串,看我的更新。
    【解决方案2】:

    re.matchmatch 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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        试试

         re.search(r'^ftp://.*\.jpg$' ,string)
        

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

        【讨论】:

          【解决方案5】:
          import re
          
          s = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
          print(re.search("^ftp://.*\.jpg$", s).group(0))
          

          【讨论】:

            【解决方案6】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-07-06
              • 1970-01-01
              • 2022-07-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-04-03
              • 2016-02-06
              相关资源
              最近更新 更多