Skip to main content
 首页 » 编程设计

Python 正则表达式\W : with vs without parenthesis

2025年05月04日25zhengyun_ustc

下面是一个快速演示。使用 \W 匹配非单词并拆分给定的字符串。为什么有括号和没有括号有区别?

>>> s = "abc:def:ghi" 
>>> p = "(\W+)" 
>>> q = "\W+" 
>>> import re 
>>> re.split(p, s, flags=re.UNICODE) 
['abc', ':', 'def', ':', 'ghi'] 
>>> re.split(q, s, flags=re.UNICODE) 
['abc', 'def', 'ghi'] 

请您参考如下方法:

来自re module文档:

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.

作为引用,将正则表达式的一部分包裹在括号中会创建一个捕获组。这些是模式组,以后可以作为单独的实体引用。