代码之家  ›  专栏  ›  技术社区  ›  SkyWalker

如何从与给定正则表达式匹配的字符串中提取int值?

  •  0
  • SkyWalker  · 技术社区  · 1 年前

    我有一个数据库url,看起来像 sqlite+pool:///C:/temp/test.db?max_connections=20&stale_timeout=300 我想提取 20 价值

    我会做一些类似的事情:

    url = 'sqlite+pool:///C:/temp/test.db?max_connections=20&stale_timeout=300'
    
    # default value
    max_connetions = 5
    if url.count('max_connections') > 0:
       # work the magic the regex would be something like
       # ".*(max_connections=)[0-9]+&.*" then $2 to get it .. or?
       max_connections = ...
    
    2 回复  |  直到 1 年前
        1
  •  2
  •   Andrej Kesely    1 年前

    你可以试试 urllib.parse :

    from urllib.parse import parse_qs, urlparse
    
    url = "sqlite+pool:///C:/temp/test.db?max_connections=20&stale_timeout=300"
    
    q = parse_qs(urlparse(url).query)
    
    max_connections_value = q.get("max_connections", [None])[0]
    print("max_connections:", max_connections_value)
    

    打印:

    max_connections: 20
    
        2
  •  1
  •   twizy    1 年前

    你可以试试这样的东西。

    import re
    
    url = "sqlite+pool:///C:/temp/test.db?max_connections=20&stale_timeout=300"
    match = re.search(r"max_connections=(\d+)", url)
    
    if match:
        max_connections_value = match.group(1)
        print(max_connections_value)
    else:
        print("No match found")
    

    (\d+)是一个与一个或多个数字匹配的捕获组(\d表示一个数字,+表示一个或更多)。