Search code examples
pythonregexregex-lookaroundsregex-groupregex-greedy

Regex for capturing digits in a string (Python)


I'm new to python & I'm processing a text file with regular expressions to extract ids & append a list. I wrote some python below intending to construct a list that looks like this

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

Instead I'm seeing a list structure that has a bunch of verbose tags included. I'm assuming this is normal behavior & the finditer function appends these tags when it finds matches. But the response is a bit messy & I'm not sure how to turn off/delete these added tags. See screenshot below.

enter image description here

Can anyone please help me modify the code below so I can achieve the intended structure for the list?

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
#https://stackoverflow.com/questions/12870178/looping-through-python-regex-matches
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)

Solution

  • re.finditer returns an iterator of re.Match objects.

    If you want to extract the actual match (and more specifically, the captured group, to get rid of the leading "id":), you can do something like this:

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