【发布时间】:2019-05-09 01:08:49
【问题描述】:
我有一个文本文件,我想匹配/查找/解析某些字符之间的所有字符([\n" 要匹配的文本 "\ n])。文本本身在其包含的结构和字符方面可能存在很大差异(它们可以包含所有可能的字符)。
我之前发布了这个问题(抱歉重复),但到目前为止问题无法解决,所以现在我试图更准确地解决这个问题。
文件中的文本是这样构建的:
test ="""
[
"this is a text and its supposed to contain every possible char."
],
[
"like *.;#]§< and many "" more."
],
[
"plus there are even
newlines
in it."
]"""
我想要的输出应该是一个列表(例如),将分隔符之间的每个文本作为一个元素,如下所示:
['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.', 'plus there are even newlines in it.']
我尝试使用正则表达式和两个解决方案以及我想出的相应输出来解决它:
my_list = re.findall(r'(?<=\[\n {8}\").*(?=\"\n {8}\])', test)
print (my_list)
['this is a text and its supposed to contain every possible char.', 'like *.;#]§< and many "" more.']
好吧,这个很接近。它列出了前两个元素,但不幸的是,它没有列出第三个元素,因为它里面有换行符。
my_list = re.findall(r'(?<=\[\n {8}\")[\s\S]*(?=\"\n {8}\])', test)
print (my_list)
['this is a text and its supposed to contain every possible char."\n ], \n [\n "like *.;#]§< and many "" more."\n ], \n [\n "plus there are even\nnewlines\n \n in it.']
好吧,这次包含了每个元素,但列表中只有一个元素,并且前瞻似乎没有像我想象的那样工作。
那么,什么是正确的正则表达式来获得我想要的输出? 为什么第二种方法不包括前瞻?
或者是否有更清洁、更快捷的方法来获得我想要的东西(beautifulsoup 或其他方法?)?
我非常感谢任何帮助和提示。
我正在使用 python 3.6。
【问题讨论】:
-
您的预期输出在字符串中有“newlins” - 我假设这是一个错字,您的意思是“newlines”,对吧?
-
是的,你说得对。谢谢。
标签: python regex character match findall