如何使用regex根据开始和结束搜索字符串的一部分



我的字符串看起来像:

s = ' {"start": 2542, "end": 2546, "text": "Asia", "labels": ["LOC"]}]'

我正试图获得";LOC";零件标签。我试过了:

re.match(r'"labels": [".*"]$', s).group()

但出现错误AttributeError: 'NoneType' object has no attribute 'group'

使用

import re
s = ' {"start": 2542, "end": 2546, "text": "Asia", "labels": ["LOC"]}]'
m = re.search(r'"labels": ["(.*)"]', s)
if m:
print(m.group(1))

请参阅Python证明和regex证明。

解释

--------------------------------------------------------------------------------
"labels":                '"labels": '
--------------------------------------------------------------------------------
[                       '['
--------------------------------------------------------------------------------
"                        '"'
--------------------------------------------------------------------------------
(                        group and capture to 1:
--------------------------------------------------------------------------------
.*                       any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)                        end of 1
--------------------------------------------------------------------------------
"                       '"'
--------------------------------------------------------------------------------
]                        ']'

最新更新