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

使用正则表达式提取含空格的目标键值对问题求助

Solution for Extracting Key-Value Pairs with Spaces in Values

Great question! The tricky part here is capturing values that include spaces without truncating them early. Let's break down how to solve this with regex.

Core Approach

We need to:

  1. Match the fixed Wordcap prefix for each target key
  2. Capture the actual key name (stripping the Wordcap prefix)
  3. Capture the corresponding value, which should extend until the next Wordcap-prefixed key or the end of the string

Regex Pattern

Wordcap(\w+)=([\s\S]*?)(?=\sWordcap|$)

Let's break down each component:

  • Wordcap: Matches the fixed prefix for all target keys
  • (\w+): Captures the key name (letters, numbers, underscores) — this gives us parts like data_proto_req or Total_reject
  • = : Matches the key-value separator
  • ([\s\S]*?): Non-greedily matches any character (including spaces and newlines, via [\s\S]) until...
  • (?=\sWordcap|$): A positive lookahead that stops the match when it hits either a space followed by Wordcap (the start of the next key) or the end of the string. This ensures we don't truncate values with spaces.

Example Implementation (Python)

import re

log_string = "Tue Apr 24 22:35:48 2018 53/e33 hello:55|Wordcap|abc|abc generate|6|Wordcapdata_proto_req=WINTER Wordcapdata_sample_resp=summer 2.4.5 WordcapTotal_reject=56 WordcapAddition_sum=TEA CUP ONE"

# Define the regex pattern
pattern = r'Wordcap(\w+)=([\s\S]*?)(?=\sWordcap|$)'

# Find all matches and format into the desired output format
matches = re.findall(pattern, log_string)
result = [f"{key}={value}" for key, value in matches]

print(result)

Output

['data_proto_req=WINTER', 'data_sample_resp=summer 2.4.5', 'Total_reject=56', 'Addition_sum=TEA CUP ONE']

Notes

  • If your key names include characters beyond letters/numbers/underscores, adjust the (\w+) part (e.g., use ([A-Za-z0-9_]+) for explicit control, or expand it to include allowed special characters).
  • The non-greedy *? combined with the positive lookahead ensures we correctly capture multi-word values without including parts of the next key.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:18:06