Python 删除 JSON 子字符串

4

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

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

什么是提取JSON字符串的最佳方法?括号外面的数字可以是任何东西(除了{}),包括换行符和类似的字符。
仅为明确起见,这是我想得到的结果。
  newStr = '{"1":2, "3":4}'

我认为最好的方法是使用findrfind,然后取子字符串。但是这种方法对我来说似乎太冗长了,而且它不符合Python 3.0标准(虽然我更喜欢Python 3.0,但这并非必要)。
感谢您的阅读。

关于findrfind,哪些方面不符合Python 3的规范? - Nicholas Knight
http://docs.python.org/library/string.html#deprecated-string-functions - devin
为什么不使用带有MULTILINE标志的正则表达式? - topchef
@devin:这并不是你想的意思。这些函数从“string”模块中删除,因为它们是多余的。内置的“str”类包括“find”和“rfind”,它们没有被弃用。http://docs.python.org/py3k/library/stdtypes.html#str.rfind - Nicholas Knight
1个回答

6
请注意,以下代码非常假设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)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接