Python:从固定前缀字符串中提取指定键对应值的需求
解决方案
针对这种包含固定键名的半结构化字符串,最直接的方式是用正则表达式精准匹配目标键值对,以下是实现代码:
import re def extract_target_value(raw_str, target_key): # 构造正则模式,适配键名带空格的情况,自动转义特殊字符 regex_pattern = rf'"{re.escape(target_key)}":\s*"([^"]+)"' match_result = re.search(regex_pattern, raw_str) # 找到匹配则返回对应值,否则返回None return match_result.group(1) if match_result else None # 测试用例 sample_strings = [ '< Some text.... "The name is": "123456789", "The other useful thing is": "456789412", Some other text... >', '< Demo text.... "The name is": "ABCDEFG", "The other useful thing is": "HIJKLMN", Extra text... >' ] # 批量提取并输出结果 for string in sample_strings: name_val = extract_target_value(string, "The name is") other_val = extract_target_value(string, "The other useful thing is") print(f"提取结果:名称={name_val},其他信息={other_val}")
代码说明
re.escape(target_key):自动转义键名中的空格、特殊字符,避免正则语法错误- 正则模式
'"{target_key}":\s*"([^"]+)"':精准匹配"键名": "值"的结构,\s*忽略键值对之间的空格,([^"]+)捕获双引号内的所有内容(即目标值) - 函数兼容未找到目标键的情况,此时返回
None,可根据实际需求调整处理逻辑
内容的提问来源于stack exchange,提问作者Andrea Canzio
相关产品推荐
相关产品推荐

