正则表达式,用于捕获字符串中的数字(Python)

时间:2019-05-12 00:29:18

标签: python regex regex-lookarounds regex-group regex-greedy

我是python的新手,我正在使用正则表达式处理文本文件以提取ID和附加列表。我在下面写了一些python,打算构造一个像这样的列表

mitmdump -s your-script.py

相反,我看到的是一个列表结构,其中包含一堆详细标签。我假设这是正常行为,并且finditer函数在找到匹配项时会追加这些标签。但是响应有点混乱,我不确定如何关闭/删除这些添加的标签。请参见下面的屏幕截图。

enter image description here

任何人都可以帮助我修改下面的代码,以便实现列表的预期结构吗?

["10073710","10074302","10079203","10082213"...and so on]

3 个答案:

答案 0 :(得分:1)

re.finditer返回iterator个对象中的一个re.Match

如果要提取实际匹配项(更具体地说,是捕获的组,以摆脱开头的"id":),可以执行以下操作:

for match in re.finditer(pattern, line_list):
    company_id.append(match.group(1))

答案 1 :(得分:0)

要获取值,请使用id.string

for id in re.finditer(pattern, line_list): 
  company_id.append(id.string)

就像在阅读id一样,您并没有获取实际值。

答案 2 :(得分:0)

如果您的数据使用JSON,则可能只想简单地对其进行解析。


如果您想使用正则表达式,则可以简化表达式,并使用三个捕获组轻松获得所需的ID。您可以在ID的左侧和右侧设置两个捕获组,然后中间的捕获组可以帮助您获取ID,也许类似于this expression

("id":")([0-9]+)(") 

enter image description here

RegEx描述图

link可帮助您形象化表情:

enter image description here

Python测试

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

import re

regex = r"(\x22id\x22:\x22)([0-9]+)(\x22)"

test_str = "some other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON data"

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.

Python测试

# -*- coding: UTF-8 -*-
import re

string = "some other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON datasome other JSON data'\"id\":\"10480132\"'>some other JSON data"
expression = r'(\x22id\x22:\x22)([0-9]+)(\x22)'
match = re.search(expression, string)
if match:
    print("YAAAY! \"" + match.group(2) + "\" is a match  ")
else: 
    print(' Sorry! No matches!')

输出:

YAAAY! "10480132" is a match