用于在字符串中提取纬度的正则表达式

2024-10-02 16:30:44 发布

您现在位置:Python中文网/ 问答频道 /正文

    lrgstPlace = features[0]
    strLrgstPlace = str(lrgstPlace)
    longtide = re.match("r(lat=)([\-\d\.]*)",strLrgstPlace)
    print (longtide)

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

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)

为什么正则表达式不能匹配任何东西?结果它只给了我“没有”。你知道吗


Tags: ofrematchplacelongfeaturefeaturesprint
2条回答

我想你是想把r放在引号之外: r"(lat=)([\-\d\.]*)"

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

(?: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.

相关问题 更多 >