【问题标题】:Regular expression to match text between curly brackets [duplicate]正则表达式匹配大括号之间的文本[重复]
【发布时间】:2020-02-24 05:38:09
【问题描述】:

尝试从此代码中提取第一个打开和最后一个关闭大括号之间的文本:

<script data-json='{"gr":{"template":77234,"body":"compact"},"model":"sedan"}' type="text/plain"></script>

我尝试过使用 [.?]|{.?} 但只匹配以下内容:
{"gr":{"template":77234,"body":"compact"}

我需要得到以下信息: {"gr":{"template":77234,"body":"compact"},"model":"sedan"}

有什么建议吗?

【问题讨论】:

  • 使用 JSON 解析器。

标签: python regex web-scraping


【解决方案1】:

尝试简单

'({.+})'

然后在比赛中通过.group(1)获得第一组

【讨论】:

    【解决方案2】:

    考虑改用 BeautifulSoup:选择 &lt;script&gt; 标签,然后提取 data-json 属性:

    from bs4 import BeautifulSoup
    text = '''
    <script data-json='{"gr":{"template":77234,"body":"compact"},"model":"sedan"}' type="text/plain"></script>
    '''
    soup = BeautifulSoup(text, 'html.parser')
    script = soup.select('script[data-json]')
    jsonData = script[0]['data-json']
    print(jsonData)
    

    输出:

    {"gr":{"template":77234,"body":"compact"},"model":"sedan"}
    

    【讨论】:

    • 我刚做了。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多