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

如何用正则匹配Steam localconfig.vdf中游戏数据的配对闭合括号

提取Steam localconfig.vdf中单个游戏的完整数据块

普通正则的贪婪匹配没法处理嵌套大括号结构,会直接匹配到文件末尾的闭合括号,而非目标游戏数据块对应的配对括号。这里提供两种可行方案:

方案一:使用递归正则(需支持PCRE引擎)

如果你的正则引擎支持递归匹配(比如PHP、Perl,或Python的第三方regex库),可以用以下正则精准匹配对应游戏的完整数据块:

"1172470"\s*\{(?:[^{}]|(?R))*\}

正则说明:

  • "1172470"\s*\{:定位目标游戏ID的起始行,匹配ID、空白字符和起始左大括号
  • (?:[^{}]|(?R))*:非捕获组,要么匹配非大括号的任意字符,要么递归匹配整个模式(处理嵌套的二级大括号)
  • \}:匹配与起始左大括号对应的闭合右大括号

Python示例(需先安装regex库:pip install regex):

import regex

# 读取localconfig.vdf文件内容
with open('localconfig.vdf', 'r', encoding='utf-8') as f:
    vdf_content = f.read()

target_game_id = "1172470"
# 生成动态正则模板
pattern = fr'"{target_game_id}"\s*{{(?:[^{{}}]|(?R))*}}'
# 搜索匹配
match_result = regex.search(pattern, vdf_content)

if match_result:
    full_game_data = match_result.group()
    print(full_game_data)
else:
    print("未找到目标游戏数据")

方案二:手动计数大括号层数(兼容所有场景)

如果不想依赖特定正则引擎,手动解析是更稳妥的方式:找到目标游戏ID的起始位置后,通过计数大括号的嵌套层数,定位到对应的闭合括号。

Python示例:

# 读取localconfig.vdf文件内容
with open('localconfig.vdf', 'r', encoding='utf-8') as f:
    vdf_content = f.read()

target_game_id = "1172470"
# 定位游戏ID的起始位置
id_start_pos = vdf_content.find(f'"{target_game_id}"')
if id_start_pos == -1:
    print("未找到目标游戏ID")
else:
    # 找到游戏数据块的起始左大括号
    brace_start_pos = vdf_content.find('{', id_start_pos)
    if brace_start_pos == -1:
        print("未找到游戏数据块的起始括号")
    else:
        brace_depth = 1
        current_pos = brace_start_pos + 1
        # 遍历字符直到括号层数归0
        while brace_depth > 0 and current_pos < len(vdf_content):
            current_char = vdf_content[current_pos]
            if current_char == '{':
                brace_depth += 1
            elif current_char == '}':
                brace_depth -= 1
            current_pos += 1
        # 提取完整游戏数据块
        full_game_data = vdf_content[id_start_pos:current_pos]
        print(full_game_data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:15:58