【问题标题】:Regex matching in python 2.7 [duplicate]python 2.7中的正则表达式匹配[重复]
【发布时间】:2016-11-29 13:10:29
【问题描述】:

我是 Python 新手,想知道如何构建正则表达式模式来匹配 URL

我在 Java 中有以下代码,它可以工作。我需要在python中有一个类似的

Java:

  URI uri = new URI("http://localhost:8080")

  Matcher m = Pattern.compile("(.*)" + "/client" + "/([0-9]+)")
  .matcher(uri.getPath());

有人可以指导我在 Python 中使用等效的正则表达式

【问题讨论】:

  • @TigerhawkT3 这里基本上有两个问题:“如何从 Python 中的 URL 获取路径?”和“如何在 Python 中使用正则表达式?”这两个问题中的第一个问题被您复制的问题很好地回答了。第二个问题很可能也是重复的,但您链接到的问题肯定不相关。
  • @smarx - second answer to that question(投票率也高于接受的答案)具有完整的 URL 正则表达式。在这个问题中,我根本看不到任何东西,它询问如何在 Python 中使用正则表达式的一般情况,这很好,因为这太宽泛了,甚至无法考虑回答。副本是理想的。
  • @TigerhawkT3 这里的问题是如何使用正则表达式从“/foo/client/12345”之类的字符串中获取“/foo”和“12345”。副本中的第二个问题也完全不相关。

标签: java python regex python-2.7


【解决方案1】:

为什么不使用urlparse?包括电池:-)。

>>> import urlparse
>>> urlparse.urlparse("http://localhost:8080")
ParseResult(scheme='http', netloc='localhost:8080', path='', params='', query='', fragment='')

【讨论】:

    【解决方案2】:

    这是 Python 2.7 中的等价物:

    import re
    from urlparse import urlparse
    
    url = urlparse('http://localhost:8080')
    
    match = re.match(r'(.*)/client/([0-9]+)', url.path)
    

    编辑

    以下是您将如何使用 match 来获取各个组件(只是猜测您接下来要做什么):

    if match:
        prefix = match.group(1)
        client_id = int(match.group(2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多