Python正则表达式:拆分冒号前含空格/非字母字符的字符串
Split String with Python re Module (Preserve Special Characters in Prefix)
Got it, let's solve this problem. The core challenge here is that we need to split the string at colon followed by space (: ) instead of just any colon—since the prefix (like Mark:))) or De'Angelo) can contain colons, apostrophes, spaces, and other special characters.
Approach
Use re.findall() with a regex pattern that captures two groups for each entry:
- The full prefix (including spaces, apostrophes, extra colons) up to the
:separator. - The corresponding message content, which stops right before the next entry's
[prefix]:or the end of the string.
Solution Code
import re input_str = "De'Angelo: hey everyone. Alexander the Great: wait. Alexander the Great: this is a weird script. Mark:))): Hello." # Regex pattern to capture (prefix, message) pairs pattern = r'(.+?): (.+?)(?=\s[^:]+?: |$)' matches = re.findall(pattern, input_str) # Flatten the list of tuples into a single list result = [item for pair in matches for item in pair] print(result)
Output
["De'Angelo", 'hey everyone.', 'Alexander the Great', 'wait.', 'Alexander the Great', 'this is a weird script.', 'Mark:)))', 'Hello.']
Regex Breakdown
Let's break down the pattern to understand how it works:
(.+?): Non-greedy capture group for the prefix. It matches every character until it hits the:separator (we use lookahead to avoid consuming the separator). This preserves all special characters and spaces in the prefix.:: The literal separator we're targeting—this is what tells us where the prefix ends and the message begins.(.+?): Non-greedy capture group for the message. It matches characters until it sees the start of the next entry.(?=\s[^:]+?: |$): Positive lookahead that stops the message capture when it detects either:- A space followed by a new prefix ending with
:(e.g.,Alexander the Great:), or - The end of the string (
$).
- A space followed by a new prefix ending with
This approach ensures we don't accidentally split the prefix at internal colons and correctly extract all the required parts.
内容的提问来源于stack exchange,提问作者Agrosel
相关产品推荐
相关产品推荐

