首页 > 解决方案 > 获取python中第一次出现的字符串

问题描述

假设我的字符串是:s='[{abc:, xyz}, {something}, {and so on}]'

我想首先出现 and 之间的所有内容{}即在这种情况下它将是{abc:, xyz}

这是我试过的

import re

s='[{abc:, xyz}, {something}, {and so on}]'

re.findall('(\{.*\})', s)[0]

标签: pythonre

解决方案


import re

pattern = r'\{\w+\s*:,*\s*\w+\}'
s='[{abc:, xyz}, {abcd: 890}, {a :908}]'
res = re.findall(pattern, s)
print(res[0]) # output {abc:, xyz}

推荐阅读