带python的正则表达式

2024-06-16 14:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取一个文件,它应该以[{"linkId":"changeDriveLink"开始,以,"zone"之前的文本结束

我的意见是:

[{"linkIdsd":"changeDridsdve [{"linkId":"changeDriveLink","url":"/drive
/3696434","zoneId":"forceAjax"},{"linkId":"printProductsFormSubst","url":"/drive/rayon.pagetemplate.substitutionlist.printproductsformsubst","zoneId":"forc
,"zone"

我想要:

[{"linkId":"changeDriveLink","url":"/drive
    /3696434","zoneId":"forceAjax"},{"linkId":"printProductsFormSubst","url":"/drive/rayon.pagetemplate.substitutionlist.printproductsformsubst","zoneId":"forc

我怎么用regex来做这个?你知道吗


Tags: 文件文本urlzonedrivepagetemplatezoneidforc
2条回答

正则表达式

re.compile(r'^\[\{"linkId":"changeDriveLink".*,"zone"', re.DOTALL)

应该这样做。中间的.*表示任何字符,re.DOTALL确保即使是换行符也匹配,以防您的json打印得很漂亮。你知道吗

但我认为最好是用json包加载文件,然后检查它是否满足您的要求:

import json

with open('filename_here.json', 'r') as json_file:
    data = json.load(json_file)

if data[0]['linkId'] == 'changeDriveLink':
    # then its OK
else:
    # not OK

根据给定的字符串,json是一个list(数组),它的第一个元素是dictdict有一个值为'linkId''linkId'键。这就是我在if语句中检查的内容。你知道吗

编辑:

现在我明白你想做什么了。 首先,应该在表达式的begging中省略^字符,因为您提供的字符串不是json文件的开始,它应该是结果的开始。 然后,您可以通过分组等方式获得所需的字符串:

pattern = re.compile(r'.*(?P<result>\[\{"linkId":"changeDriveLink".*),"zone"', re.DOTALL)
match_obj = pattern.match('your_json_string')
if match_obj is not None:
    the_string_you_want = match_obj.group('result')

我在这里使用的是命名分组,您可以在documentation中了解更多

IMHO,使用json包并在结构中搜索要比编写复杂的regex好得多,因为它不可读并且很难调试。你知道吗

你可以访问这个帖子(Parsing json and searching through it)来获取更多的想法。你知道吗

相关问题 更多 >