【问题标题】:Extract a string between double quotes提取双引号之间的字符串
【发布时间】:2014-03-29 18:56:03
【问题描述】:

我正在阅读来自期刊或论文来源的回复,并且我将 html 回复作为字符串,例如:

根据一些人的说法,梦表达了“个性的深刻方面”(Foulkes 184),尽管其他人不同意。

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

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

不知何故,它对我不起作用。对我的正则表达式有任何帮助吗?非常感谢。

【问题讨论】:

  • 这甚至不是有效的 Python(语法错误)并且没有 re.Matches() 函数。

标签: python regex string


【解决方案1】:

如果没有嵌套引号:

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']

【讨论】:

  • 谢谢,这对我有用。我有一个额外的问题,假设学生的论文需要在任何引号之前有一个半冒号,比如——梦想表达:“...的深刻方面”,我怎么能只添加双引号中的子字符串,后跟半冒号?
  • 您的意思是您只想匹配:<whitespace>"(text to extract)"?然后在正则表达式中的第一个" 字符之前添加:\s*
  • re.findall(r':\s*"([^"]*)"', inputString),你能解释一下为什么我们需要*吗?
  • @Kiddo: 匹配 0 个或多个空格。灵活性。
【解决方案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

使用(?&lt;!\\) 否定后视它检查" 之前是否有\

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2021-10-20
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多