如何在python中遍历正则表达式对象
我有以下python小程序:如何在python中遍历正则表达式对象,python,regex,Python,Regex,我有以下python小程序: from inspect import getmembers from pprint import pprint import re def text_function(): text = '{"device_ip_address": "10.2.16.221", "device_port": 55550, "server_port": 50100, "protocol": "gsm", "bundled_messages": [{"device_ip_a
from inspect import getmembers
from pprint import pprint
import re
def text_function():
text = '{"device_ip_address": "10.2.16.221", "device_port": 55550, "server_port": 50100, "protocol": "gsm", "bundled_messages": [{"device_ip_address": "10.2.16.221", "device_port": 55550, "bundled_messages": [{"device_ip_address": "10.2.16.221", "device_port": 55550, "unit_id": 1770, "message_size": 12, "protocol_version": 2, "message_id": 18, "timestamp": "2014-05-22 21:17:16", "num_retries": 0, "message_token": 0, "command_id": 0, "number_of_blocks": 0, "unused": 0, "battery_level_external": 0, "battery_level_internal": 100, "alert_flag04": 0, "alert_flag03": 0, "alert_flag02": 0, "alert_flag01": 0, "gsm_rssi": 0, "gps_average_snr": 0, "satellite_count": 0, "status_flag06": 0, "status_flag05": 0, "status_flag04": 0, "status_flag03": 0, "status_flag02": 0, "status_flag01": 0, "battery_charging_fault": 0, "battery_charging_state": 0, "type": "ant_no_communication_failure_alert", "type_specific_data": 0, "message_name": "geoalert", "blocks": []}], "unit_id": 1770, "message_size": 24, "protocol_version": 2, "message_id": 24, "timestamp": "2014-05-22 00:00:38", "num_retries": 0, "message_token": 0, "message_name": "warehouse"}], "unit_id": 1308, "protocol_version": 2, "message_id": 24, "num_retries": 0, "message_token": 6, "timestamp": "2014-05-22 21:17:16", "message_name": "warehouse"}'
a = re.compile(r'.*"bundled_messages": ([\[][{].*[}][\]])')
b = a.match(text)
return b
def processBundleMessage(bundleMessage):
return bundleMessage
print processBundleMessage(text_function())
运行时打印出以下内容:
。问题是,我想仔细检查一下,并在这里取出每个匹配项,这样我就可以单独处理这些匹配项
我可以这样做:
bundleMessage.lastindex
它给我提供了1
告诉我这里有两个匹配项,我可以使用group(x)
获得一个特定的匹配项,但有时可能会有100个或更多匹配项。那么,我该如何理解这句话——让我拥有所有的比赛呢?也许我没有解决好这个问题,但你为什么不试试这样的方法呢
a = processBundleMessage(text_function())
for i in range(a.lastindex + 1):
print('====')
print(a.group(i))
您的文本是JSON数据。为什么不使用json标准库并返回一个更容易处理的字典呢 正如前面提到的,最好使用json库。不过,看看下面的例子也没什么坏处: match对象有一个名为
groups()
的函数,它列出了它的所有匹配项
matches = text_function()
if matches: # check if there is any match
print matches.groups() # prints a tuple of all matches
用于b.groups()中的组。
?你读过吗?迭代索引的范围
很少是python式的-在这种情况下,你可以调用a.groups()
来获得匹配的元组,然后迭代。
matches = text_function()
if matches: # check if there is any match
print matches.groups() # prints a tuple of all matches