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.
Code
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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.