Skip to main content
 首页 » 编程设计

python之拆分字符串时正则表达式模式中的括号

2025年05月04日13jackei

我想知道以下行为背后的原因:

>>> re.compile("(b)").split("abc")[1] 
'b' 
>>> re.compile("b").split("abc")[1] 
'c' 

我似乎在拆分模式周围添加括号时,将其重新添加到拆分数组中。但为什么?它是一致的,还是只是正则表达式的孤立特征。

请您参考如下方法:

根据 documentation,这是 re.split 的一个特性:

If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

通常,括号表示捕获组,用于提取字符串的某些部分。阅读更多关于 capture groups 的信息.