You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串字典转Dict前的格式化需求:正则替换逗号时排除引号后紧跟的逗号

Fixing the Regex to Avoid Breaking Array Values

Got it, let's sort out this regex problem for you! The issue with your original pattern is that it matches all commas between digits—including the ones inside arrays like fingerOne_OffTimes, which you want to leave untouched.

The Solution: Target Only Non-Array Digit Commas

We need a regex that matches commas between digits, but only if those commas aren't inside a [ ... ] array block. Here's the adjusted pattern and how it works:

import re
import json

# Your original string
dict_str = '{"level":0,6, "params":{ "startLvlTime":1114.3851318359375, "fingerOne_OffTimes":[459,4716491699219,78532]}}'

# The corrected regex pattern
decmark_reg = re.compile(r'(?<=\d),(?=\d)(?=(?:[^[\]]*\])*[^[\]]*$)')

# Replace commas with dots only where needed
dict_decmark = decmark_reg.sub('.', dict_str)

# Convert to dictionary
convertedDict = json.loads(dict_decmark)

print(convertedDict)

What the Regex Does

Let's break down the pattern (?<=\d),(?=\d)(?=(?:[^[\]]*\])*[^[\]]*$):

  • (?<=\d): Positive lookbehind to ensure the comma is preceded by a digit.
  • ,(?=\d): Positive lookahead to ensure the comma is followed by a digit.
  • (?=(?:[^[\]]*\])*[^[\]]*$): This is the key part—it checks that from the comma's position to the end of the string, every opening [ has a matching closing ]. This guarantees the comma isn't inside an unclosed array block (i.e., it's safely in an object's key-value pair).

Result

After running the code, you'll get exactly what you want:

{'level': 0.6, 'params': {'startLvlTime': 1114.3851318359375, 'fingerOne_OffTimes': [459, 4716491699219, 78532]}}

The 0,6 is converted to 0.6, while the commas inside the fingerOne_OffTimes array stay intact.

内容的提问来源于stack exchange,提问作者kubaSpolsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:58:12