Java正则转Python适配请求:移除JSON中body字段引号内逗号
解决Python中无法运行Java正则表达式的问题
问题背景
- 原Java可用的正则表达式:
r"""(\G(?!^)|\"body\"\s*:\s*\")([^\",]*),""" - 在Python中运行时报错:
bad escape \G at position 1,原因是Python的re模块不支持\G锚点(该锚点用于匹配上一次匹配结束的位置,实现连续匹配) - 需求:替换JSON文件中
"body"键对应字符串值内的所有逗号
替代解决方案
方案1:正则+回调函数(适合简单JSON结构)
通过正则匹配"body"键的完整值,单独处理值内的逗号:
import re def clean_body_commas(json_content): def process_body(match): # 捕获引号内的body值,去除其中的逗号 return f'"body": "{match.group(1).replace(",", "")}"' # 匹配"body": "xxx"格式,捕获xxx部分 pattern = r'"body"\s*:\s*"([^"]*)"' return re.sub(pattern, process_body, json_content) # 测试示例 test_content = '''{ "id": 2, "body": "a,b,c,d", "desc": "keep,commas,here" }''' print(clean_body_commas(test_content))
方案2:解析JSON后处理(更稳妥,支持复杂JSON)
用Python内置json模块解析文件,修改body值后重新写入,避免正则处理转义字符的问题:
import json def clean_json_body(file_path): # 读取并解析JSON with open(file_path, 'r', encoding='utf-8') as f: json_data = json.load(f) # 处理body字段的逗号 if 'body' in json_data and isinstance(json_data['body'], str): json_data['body'] = json_data['body'].replace(',', '') # 写回文件 with open(file_path, 'w', encoding='utf-8') as f: json.dump(json_data, f, indent=4) # 调用示例(替换为你的JSON文件路径) # clean_json_body('data.json')
内容的提问来源于stack exchange,提问作者ThePeres
相关产品推荐
相关产品推荐

