侧边栏壁纸
  • 累计撰写 2,046 篇文章
  • 累计创建 73 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

Python仅使用正则表达式提取json值

大猿本猿
2021-07-08 / 871 阅读 / 0 字

我有一个嵌入在json中的描述字段,并且无法使用json库解析此数据。

{0,23}为了顺序尝试提取字符串的前23个字符,如何提取与说明相关的整个值?

   import re

    description = "'\description\" : \"this is a tesdt \n another test\" "

    re.findall(r'description(?:\w+){0,23}', description, re.IGNORECASE)

对于上述代码,仅['description']显示


解决方案


您可以尝试以下代码:

import re

description = "description\" : \"this is a tesdt \n another test\" "

result = re.findall(r'(?<=description")(?:\s*\:\s*)(".{0,23}?(?=")")', description, re.IGNORECASE+re.DOTALL)[0]

print(result)

得到的结果如下:

"this is a tesdt 
 another test"

本质上是:

\"this is a tesdt \n another test\"

这就是您在评论中要求的。


说明-

(?<=description")是一个正向后面,告诉正则表达式与前面的文本匹配description"
(?:\s*\:\s*)是一个非捕获组,它告诉正则表达式description"后面将是零个或多个空格,冒号(:)和零个或多个空格。
(".{0,23}?(?=")")是所需的实际匹配项,它由双引号("),零至二十三个字符和最后的双引号(")组成。