技术求助:协助实现以冒号为分隔符的字符串键值对拆分
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 likeone_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 (
$).
- One or more spaces followed by a key and colon (
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
相关产品推荐
相关产品推荐

