【问题标题】:Extracting strings in Python in either single or double quotes在 Python 中用单引号或双引号提取字符串
【发布时间】:2013-11-09 15:26:24
【问题描述】:

我需要 Python 正则表达式的帮助来提取单引号或双引号内的字符串。我找到了一个解决方案,但正则表达式在 C# 中:

How to extract the string in the quotes (either double quotes or single quotes)

我需要解析这个字符串

tags = { 'one' : "two", "three", 'four' }

并返回数组项:

one
two
three
four

目前我有这个单引号:

quoted = re.findall(r"'(.*?)'", buffer, re.DOTALL)      

【问题讨论】:

    标签: python regex string quotes findall


    【解决方案1】:
    >>> buffer="tags = { 'one' : \"two\", \"three\", 'four' }"
    >>> re.findall(r"['\"](.*?)['\"]", buffer)
    ['one', 'two', 'three', 'four']
    

    【讨论】:

    • 知道了,谢谢!有什么方法可以返回每个项目使用的报价吗?
    • @Ron Saying re.findall(r"(['\"])(.*?)['\"]", buffer) 会给你一个元组列表。
    • 如果值包含转义引号或其他类型的引号,这将失败。后者您可以通过使用反向引用作为结束引号来修复,例如(['\"])(.*?)\1
    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 2011-01-27
    • 2023-02-23
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    相关资源
    最近更新 更多