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

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:

  1. The full prefix (including spaces, apostrophes, extra colons) up to the : separator.
  2. 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 ($).

This approach ensures we don't accidentally split the prefix at internal colons and correctly extract all the required parts.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:10:56