在Hi中编写Regex表达式

2024-06-27 09:23:08 发布

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

假设以下是我的数据

string

&geoLati=33.75875&
&loclat=39.5586&
&ang_lat_add_one_more=35.4789&
&slat=45.2563&
&LAT=12.5698&
&vloclat=65.4789&
&latpoi=35.2478&
&lat_lkj=25.6523&
&someother_lat=25.6523&
&lat=65.3214&lat=98.4562&

我有一个长字符串(URL),我想检查字符串中是否存在lat关键字,然后检查最近的“=”符号并解析出值,直到出现下一个“&;”。理想情况下,我想写一个表达式,将剥离值单独从上述数据集。你知道吗

以下是我的尝试

select regexp_extract(string, 'lat=(.*?)(&)') as output

这似乎适用于大多数人,但不适用于少数人。以下是输出

 output
        ""
        39.5586
        ""
        45.2563
        ""
        65.4789
        ""
        ""
        25.6523
        65.3214

有人能帮我修改表达式以得到所有的值吗?我想检查关键字lat而不考虑大小写,并查找最接近的“=”符号,然后解析值直到下一个“&;”。你知道吗

我的预期产出是

output
33.75875
39.5586
35.4789
45.2563
12.5698
65.4789
35.2478
25.6523
25.6523
65.3214

任何帮助都将不胜感激。你知道吗

谢谢


Tags: 数据字符串addoutputstring表达式more符号
2条回答

你可以用

(?i)lat\w*=([^&]+)

参见regex demo。他说

详细信息:

  • (?i)-不区分大小写模式
  • lat-文字字符序列
  • \w*-0+字字符
  • ^{cd4}符号
  • ([^&]+)-组1:除&之外的一个或多个字符。你知道吗

在配置单元中,使用双反斜杠:

select regexp_extract( "&lati=35.2478&" , '(?i)lat\\w*=([^&]+)') as output 

这应该管用。他说

(\b\d.+)

输入:

&geoLati=33.75875&
&loclat=39.5586&
&ang_lat_add_one_more=35.4789&
&slat=45.2563&
&LAT=12.5698&
&vloclat=65.4789&
&latpoi=35.2478&
&lat_lkj=25.6523&
&someother_lat=25.6523&
&lat=65.3214&lat=98.4562&

输出:

75875&
5586&
4789&
2563&
5698&
4789&
2478&
6523&
6523&
4562&

Python代码:

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(\b\d.+)"

test_str = ("&geoLati=33.75875&\n"
    "&loclat=39.5586&\n"
    "&ang_lat_add_one_more=35.4789&\n"
    "&slat=45.2563&\n"
    "&LAT=12.5698&\n"
    "&vloclat=65.4789&\n"
    "&latpoi=35.2478&\n"
    "&lat_lkj=25.6523&\n"
    "&someother_lat=25.6523&\n"
    "&lat=65.3214&lat=98.4562&")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 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.

见:https://regex101.com/r/causfX/2

相关问题 更多 >