python – 在花括号内部用空格保留字符串
发布时间:2020-12-20 12:08:23 所属栏目:Python 来源:网络整理
导读:str = "cmd -opt1 { a b c d e f g h } -opt2" 我想要这样的输出: [ 'cmd','-opt1','{ a b c d e f g h }','-opt2' ] 解决方法 在这种情况下,不要尝试拆分,使用re.findall: import re re.findall(r'{[^}]*}|S+','cmd -opt1 { a b c d e f g h } -opt2')['
str = "cmd -opt1 { a b c d e f g h } -opt2" 我想要这样的输出: [ 'cmd','-opt1','{ a b c d e f g h }','-opt2' ] 解决方法
在这种情况下,不要尝试拆分,使用re.findall:
>>> import re >>> re.findall(r'{[^}]*}|S+','cmd -opt1 { a b c d e f g h } -opt2') ['cmd','-opt2'] 如果你必须处理嵌套的花括号,re模块是不够的,你需要使用具有递归功能的“new” regex module. >>> import regex >>> regex.findall(r'[^{}s]+|{(?:[^{}]+|(?R))*+}','cmd -opt1 { a b {c d} e f} -opt2') ['cmd','{ a b {c d} e f}','-opt2'] 其中(?R)指的是整个模式本身. 或者这个(更好): regex.findall(r'[^{}s]+|{[^{}]*+(?:(?R)[^{}]*)*+}','cmd -opt1 { a b {c d} e f} -opt2') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |