简体   繁体   English

使用正则表达式提取嵌入在大括号内的 [] 内的内容

[英]Extracting content within[] embedded inside curly brackets using Regex

I have a string in the following format我有以下格式的字符串

test_str = '{"keywords": {"Associate Director Information Technology Services": ["Director of Technology Services"]}}'

My Regex code below我的正则表达式代码如下

import re
matches= re.findall(r'\{(.*?)\}',test_str)

gives the output给出 output

['"keywords": {"Associate Director  Information Technology Services": ["Director of Technology Services"]']

What change should I do in my Regex expression to output only我应该在我的正则表达式中对 output 做哪些更改

"Director of Technology Services"
re.findall(r"\[(.*?)\]", test_str)

print(re.findall(r"\[(.*?)\]", test_str)[0])

instead of escaping { and } you should escape [ and ] .而不是 escaping {}你应该转义[]
Alternative Solution using capturing of groups.使用组捕获的替代解决方案。

import re

regex = re.compile(r"\[(.*?)\]")
test_str = '{"keywords": {"Associate Director Information Technology Services": ["Director of Technology Services"]}}'

print(regex.search(test_str).group(1))

Output: Output:

"Director of Technology Services"

Try using the below code:尝试使用以下代码:

import json
test_str = '{"keywords": {"Associate Director Information Technology Services": ["Director of Technology Services"]}}'
test_str_json = json.loads(test_str)
output = test_str_json["keywords"]["Associate Director Information Technology Services"][0]
print(output)

Output: Output:

Director of Technology Services

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM