是re.split(“\ W”)= re.split(“\ w”)?

时间:2017-02-27 11:31:11

标签: python python-3.x split

正如标题所说,re.split("\W")re.split("\w")相同,因为我得到的结果与我使用的结果相同。如果它有+,也是如此。这是正确的吗?或者它在某些情况下有效,如果是,为什么?提前谢谢。

1 个答案:

答案 0 :(得分:3)

它们根本不是一回事:

>>> test_string = 'hello world'
>>> import re
>>> re.split('\w', test_string)
['', '', '', '', '', ' ', '', '', '', '', '']
>>> re.split('\W', test_string)
['hello', 'world']

re.split执行以下操作:

  

按照模式的出现拆分源字符串,       返回包含结果子字符串的列表。

\w\W是:

\w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
         With LOCALE, it will match the set [0-9_] plus characters defined
         as letters for the current locale.
\W       Matches the complement of \w.