使用正则表达式提取含空格的目标键值对问题求助
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:
- Match the fixed
Wordcapprefix for each target key - Capture the actual key name (stripping the
Wordcapprefix) - 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 likedata_proto_reqorTotal_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 byWordcap(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
相关产品推荐
相关产品推荐

