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

Regex for capturing digits in a string (Python)

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

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

相反,我看到的是一个包含一堆冗长标签的列表结构。我假设这是正常行为 & finditer 函数在找到匹配项时附加这些标签。但是响应有点乱,我不确定如何打开 off/delete 这些添加的标签。请参见下面的屏幕截图。

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

import re

#create a list of strings
company_id = []

#open file contents into a variable
company_data = open(r'C:\Users\etherealessence\Desktop\company_data_test.json', 'r', encoding="utf-8")

#read the line structure into a variable
line_list = company_data.readlines()

#stringify the contents so regex operations can be performed
line_list = str(line_list)

#close the file
company_data.close()

#assign the regex pattern to a variable
pattern = re.compile(r'"id":([^,]+)')

#find all instances of the pattern and append the list
#
for id in re.finditer(pattern, line_list): 
  #print(id)
  company_id.append(id)

#test view the list of company id strings
#print(line_list)
print(company_id)

要获取值,请使用 id.string:

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

当您只读取 id 时,您并没有获取实际值。

如果您的数据在 JSON 中,您可能只想简单地解析它。


如果你想使用正则表达式,你可以简化你的表达式并使用三个捕获组来更容易地获得所需的 ID。你可以在你的ID的左右两边分别设置两个捕获组,然后中间的捕获组可以帮你获取ID,可能类似于this expression

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

正则表达式描述图

这个link可以帮助你形象化你的表情:

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 

re.finditer returns iteratorre.Match 个对象。

如果你想提取实际的匹配项(更具体地说,捕获的组,以摆脱前导 "id":),你可以这样做:

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