【问题标题】:RegEx for extracting latitude in a string用于在字符串中提取纬度的正则表达式
【发布时间】:2026-02-01 02:05:01
【问题描述】:
    lrgstPlace = features[0]
    strLrgstPlace = str(lrgstPlace)
    longtide = re.match("r(lat=)([\-\d\.]*)",strLrgstPlace)
    print (longtide)

这就是我的功能列表的样子

特征(地点='玻利维亚克利扎南 28 公里',长=-65.8913,纬度=-17.8571,深度=358.34,mag=6.3) Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)

为什么正则表达式不能匹配任何东西?结果它只是给我“无”。

【问题讨论】:

  • r 移出正则表达式...
  • 您可能也不想捕获“lat”,而只想捕获后面的数字:r"lat=([\-\d\.]*)"
  • 您可能还需要re.search 而不是re.match

标签: python regex python-3.x regex-lookarounds regex-group


【解决方案1】:

我认为您的意思是将 r 放在引号之外: r"(lat=)([\-\d\.]*)"

【讨论】:

    【解决方案2】:

    您的原始表达式工作正常,如果我们只想提取纬度数字,我们可能需要稍微修改一下:

    (?:lat=)([0-9\.\-]+)(?:,)
    

    ([0-9\.\-]+) 将捕获我们想要的 lat,我们用两个非捕获组包裹它:

    (?:lat=)
    (?:,)
    
    DEMO

    测试

    # coding=utf8
    # the above tag defines encoding for this document and is for Python 2.x compatibility
    
    import re
    
    regex = r"(?:lat=)([0-9\.\-]+)(?:,)"
    
    test_str = "Feature(place='28km S of Cliza, Bolivia', long=-65.8913, lat=-17.8571, depth=358.34, mag=6.3) Feature(place='12km SSE of Volcano, Hawaii', long=-155.2005, lat=19.3258333, depth=6.97, mag=5.54)"
    
    matches = re.finditer(regex, test_str, re.MULTILINE)
    
    for matchNum, match in enumerate(matches, start=1):
    
        print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
    
        for groupNum in range(0, len(match.groups())):
            groupNum = groupNum + 1
    
            print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
    
    # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
    

    【讨论】:

      最近更新 更多