在双引号之间提取字符串

2024-09-20 03:59:11 发布

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

我正在阅读一篇来自某个来源的回复,该来源是一篇日志或一篇文章,我的html回复是一个字符串,如:

According to some, dreams express "profound aspects of personality" (Foulkes 184), though others disagree.

我的目标是从给定字符串中提取所有引号,并将它们保存到一个列表中。我的方法是:

[match.start() for m in re.Matches(inputString, "\"([^\"]*)\""))]

不知怎么的,这对我不起作用。对我的regex有什么帮助吗?谢谢。


Tags: ofto字符串html文章来源someexpress
2条回答

如果您的输入可以有如下内容,请使用这个:some "text \" and text" more

s = '''According to some, dreams express "profound aspects of personality" (Foulkes 184), though others disagree.'''
lst = re.findall(r'"(.*?)(?<!\\)"', s)
print lst

使用(?<!\\)负lookbehind检查在"之前没有\

如果没有嵌套引号:

re.findall(r'"([^"]*)"', inputString)

演示:

>>> import re
>>> inputString = 'According to some, dreams express "profound aspects of personality" (Foulkes 184), though others disagree.'
>>> re.findall(r'"([^"]*)"', inputString)
['profound aspects of personality']

相关问题 更多 >