正则表达式匹配含分隔符的键值对:值含分隔符时匹配异常求助
Fixing Regex for Key-Value Pairs with Embedded Separators
Your current regex ([A-Za-z0-9_]+)=((.*?)+)• falls short because the non-greedy .*? stops at the first occurrence of •, which cuts off your value prematurely when it contains the separator.
To solve this, we need to tell the regex to keep matching the value until it hits either the start of the next key-value pair or the final trailing • at the end of the string. Here's the adjusted regex:
([A-Za-z0-9_]+)=(.*?)(?=•[A-Za-z0-9_]+=|•$)
How It Works:
([A-Za-z0-9_]+): Captures the key (matches your allowed key characters: letters, numbers, underscores).=: Matches the literal equals sign separating key and value.(.*?): Non-greedy match for the value — it stops as soon as the lookahead condition is met.(?=•[A-Za-z0-9_]+=|•$): A positive lookahead that checks for either:•[A-Za-z0-9_]+=: The separator followed by a new key and equals sign (signaling the start of the next pair), or•$: The separator at the end of the string (signaling the end of the last pair).
Testing Against Your Example String:
For the input:
MY_KEY_1=○•◘♠ ♥•MY_KEY_2=as dfa sd f@#$•
The regex will capture two matches:
- Group 1:
MY_KEY_1, Group 2:○•◘♠ ♥→ Combined result:MY_KEY_1=○•◘♠ ♥ - Group 1:
MY_KEY_2, Group 2:as dfa sd f@#$→ Combined result:MY_KEY_2=as dfa sd f@#$
Which exactly matches your expected output!
Quick Adjustment for Edge Cases:
If your input might not have a trailing • at the end, tweak the lookahead to (?=•[A-Za-z0-9_]+=|$) to handle that scenario smoothly.
内容的提问来源于stack exchange,提问作者Raziza O
相关产品推荐
相关产品推荐

