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

技术求助:协助实现以冒号为分隔符的字符串键值对拆分

Solution for Splitting Key-Value Pairs with Colon Delimiters

Got it, let's tackle this problem. The main challenge here is that a simple split on every colon won't work—we need to distinguish between colons that separate keys from values, and stop capturing a value only when we hit the next "key: " pattern (or the end of the string).

Approach

We can use a regular expression to match each key-value pair explicitly. The regex will:

  • Identify keys as word-like identifiers (including underscores, since your example has one_more) followed by a colon.
  • Capture values as everything from the colon until the next "space + key + colon" sequence, or the end of the string.

Code Example (Python)

import re

input_str = "somekey:value1 value2 another:<value3 one_more:value4..value5"
# Regex pattern to match key-value pairs
pattern = r'(\w[\w_]*):(.*?)(?=\s+\w[\w_]*:|$)'
key_value_pairs = re.findall(pattern, input_str)

# Output the result in your desired format
for key, value in key_value_pairs:
    print(f"<{key!r}, {value!r}>")

Output

<'somekey', 'value1 value2'>
<'another', '<value3'>
<'one_more', 'value4..value5'>

Regex Breakdown

Let's break down the pattern to understand how it works:

  • (\w[\w_]*): Captures the key. Matches a word character (letter/number/underscore) followed by any number of word characters or underscores—perfect for identifiers like one_more.
  • :: Matches the colon that separates the key from its value.
  • (.*?): Non-greedily captures the value (so it stops as soon as the next key pattern is found). The ? ensures we don't capture beyond the next key.
  • (?=\s+\w[\w_]*:|$): A positive lookahead that tells the regex to stop capturing the value when it sees either:
    • One or more spaces followed by a key and colon (\s+\w[\w_]*:), or
    • The end of the string ($).

This approach handles edge cases like values with special characters (like < in your example) and keys with underscores, which a simple split would struggle with.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:52:29