print (re.split(r'[a-fA-F]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M))
print (re.split(r'[a-fA-Z]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M))
print (re.split(r'\d*','sdfsfdsfds123212fdsf2'))
print (re.split(r'\d','sdfsfdsfds123212fdsf2'))
print (re.split(r'\w+','dsfsf sdfdsf sdfsdf sfsfd'))
['', 'inqw', 'nl', 'sk', 'jri', 'w', 's', 'S', '', '', 'dsafsafasa']
['', 'inqw', 'nl', 'sk', 'jri', 'w', 's', '', '', '', 'ddsafsafasa']
['sdfsfdsfds', 'fdsf', '']
['sdfsfdsfds', '', '', '', '', '', 'fdsf', '']
['', ' ', ' ', ' ', '']
我觉得这里的输出很奇怪。分割字符串的模式有时会在输出列表中变为“”,但有时会消失。在
不,模式(或它匹配的内容)永远不会包含在输出中。这些
''
是匹配之间的。因为这就是re.split
所做的。你的例子:按数字拆分,子字符串
'123212'
有六个数字,因此它们之间有五个空字符串。这就是为什么输出中有五个空字符串。在首先,您实际上提供了
maxsplit=10
参数,而不是flags=re.I|re.
其次,分隔符是而不是变成
''
;这是分隔符之间的字符串:请注意两个分隔符之间的
''
,并且在末尾。在分隔符本身在结果中是而不是,除非正则表达式包含捕获组(
^{pr2}$(...)
):第三:尽管
r'\d*'
通常在字符串的开头、字符串的结尾、每个字符之间的和匹配,当前只有非零长度的匹配被re.split
考虑,因此该模式的行为类似于r\d+
。但是,这种行为可能会在Python3.6及更高版本中发生更改,并在Python 3.5上发出警告FutureWarning: split() requires a non-empty pattern match.
。在输出并不奇怪,它是有意的。From the docs:
强调了为什么要这样做。这同样适用于字符串内的“空”序列和非捕获分隔符。基本上,在分隔符之前和之后都有内容-即使没有捕获分隔符,并且其中任何一个内容都是空的。类似的方法
str.split
actually does the same。在如果知道分隔符,就可以始终重建初始字符串。捕获分隔符并连接,或在连接时插入分隔符是等效的。
''.join(re.split('(%s)' % sep, ':::words::words:::')) == sep.join(re.split('%s' % sep, ':::words::words:::'))
相关问题 更多 >
编程相关推荐