簡體   English   中英

正則表達式,用於捕獲字符串中的數字(Python)

[英]Regex for capturing digits in a string (Python)

我是python的新手,正在處理帶有正則表達式的文本文件以提取id和附加列表。 我在下面寫了一些python,打算構造一個像這樣的列表

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

相反,我看到的是一個列表結構,其中包含許多冗長的標簽。 我假設這是正常行為,並且finditer函數在找到匹配項時會追加這些標簽。 但是響應有點混亂,我不確定如何關閉/刪除這些添加的標簽。 請參見下面的屏幕截圖。

在此處輸入圖片說明

誰能幫我修改下面的代碼,以便實現列表的預期結構?

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)

re.finditer返回re.Match對象的iterator

如果要提取實際匹配項(更具體地說,是捕獲的組,以擺脫開頭的"id": :),則可以執行以下操作:

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

要獲取值,請使用id.string

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

因為當您僅讀取id時,您並未獲取實際值。

如果您的數據使用JSON,則可能只想簡單地對其進行分析。


如果希望使用正則表達式,則可以簡化表達式,並使用三個捕獲組輕松獲得所需的ID。 您可以在ID的左側和右側設置兩個捕獲組,然后中間的捕獲組可以幫助您獲取ID,也許類似於以下表達式

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

在此處輸入圖片說明

RegEx描述圖

鏈接可幫助您形象化您的表情:

在此處輸入圖片說明

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 💚💚💚

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM