【问题标题】:Python remove JSON substringPython 删除 JSON 子字符串
【发布时间】:2011-12-25 12:16:35
【问题描述】:

如果我有一个字符串,其中有一个像这样的有效 JSON 子字符串:

 mystr = '100{"1":2, "3":4}312'

仅提取 JSON 字符串的最佳方法是什么?外面的数字可以是任何东西({ 或 } 除外),包括换行符和类似的东西。

明确一点,这就是我想要的结果

  newStr = '{"1":2, "3":4}'

我能想到的最好方法是使用find 和rfind,然后获取子字符串。这对我来说似乎太冗长了,并且不符合 python 3.0(我更喜欢但不是必需的)

感谢任何帮助。

【问题讨论】:

标签: python string json


【解决方案1】:

请注意,以下代码非常假设 JSON 字符串的任何一侧除了非括号材料之外没有任何其他内容。

import re
matcher = re.compile(r"""
^[^\{]*          # Starting from the beginning of the string, match anything that isn't an opening bracket
       (         # Open a group to record what's next
        \{.+\}   # The JSON substring
       )         # close the group
 [^}]*$          # at the end of the string, anything that isn't a closing bracket
""", re.VERBOSE)

# Your example
print matcher.match('100{"1":2, "3":4}312').group(1)

# Example with embedded hashmap
print matcher.match('100{"1":{"a":"b", "c":"d"}, "3":4}312').group(1)

简短、非预编译、非注释版本:

import re
print re.match("^[^\{]*(\{[^\}]+\})[^}]*$", '100{"1":2, "3":4}312').group(1)

虽然为了维护,注释正则表达式是非常受欢迎的。

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 2022-08-19
    • 2021-10-14
    • 2015-08-07
    • 2018-03-14
    • 2015-11-20
    相关资源
    最近更新 更多