我想将一个字符串分解成组件
s = 'Hello [foo] world!'
re.split(r'\[(.*?)\]', s)
这给了我
['Hello ', 'foo', ' world!']
但我想达到
['Hello ', '[foo]', ' world!']
请帮忙!
采用
import re
s = 'Hello [foo] world!'
print(re.split(r'(\[[^][]*])', s))
请参阅Python 证明。
结果:['Hello ', '[foo]', ' world!']
解释
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
[^][]* any character except: ']', '[' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
] ']'
--------------------------------------------------------------------------------
) end of \1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句