大模型开发中常用的正则表达式

Posted on 2025-08-20 20:00 in Python

提取 JSON

match = re.search(r'```json\s*([\s\S]*?)\s*```', text, re.MULTILINE)
if match:
    json_code = match.group(0)

提取出来还要去掉开头的 ```json 和 结尾的 ```

提取 XML

match = re.search(r'```xml\s*([\s\S]*?)\s*```', text, re.MULTILINE)
if match:
    xml_code = match.group(0)

提取出来还要去掉开头的 ```xml 和 结尾的 ```

去掉 think 标签

cleaned_response = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)