re.split Keeps Capture Group Separators

re.split returns capture groups alongside the fields, so delimiters stay in the result list and the original line can be rebuilt byte for byte with join.

PythonData Integrity

Code

pythonsnippet
14 lines
import re

# 捕获分组:分隔符留在结果里,字段与分隔符交替出现
parts = re.split(r"([,;])", "red,green;blue,yellow")
print(parts)
print("rejoin:", "".join(parts) == "red,green;blue,yellow")

# 非捕获分组 (?:...):分隔符被丢弃,只拿字段
fields = re.split(r"[,;]", "red,green;blue,yellow")
print(fields)

# 分组可以匹配多字符分隔符:按段落边界拆分并保留边界本身
blocks = re.split(r"(\n\n)", "intro\n\nbody\n\nsummary")
print(blocks)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

['red', ',', 'green', ';', 'blue', ',', 'yellow']
rejoin: True
['red', 'green', 'blue', 'yellow']
['introbodysummary']

How it works

Top-level bindings parts, fields, blocks hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (rejoin:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `parts`, `fields`, `blocks`.