如何根据数字/非数字拆分字符串(使用正则表达式?) [英] How to split a string (using regex?) depending on digit/ not digit
本文介绍了如何根据数字/非数字拆分字符串(使用正则表达式?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在python中将一个字符串拆分为一个列表,具体取决于数字/不是数字.例如,
5 55+6+ 5/
应该返回
['5','55','+','6','+','5','/']
我现在有一些代码循环遍历字符串中的字符并使用 re.match("\d") 或 ("\D") 测试它们.我想知道是否有更好的方法来做到这一点.
P.S:必须兼容python 2.4
解决方案
假设 6 和 5 之间的 +
需要匹配(你错过了),
I want to split a string into a list in python, depending on digit/ not digit. For example,
5 55+6+ 5/
should return
['5','55','+','6','+','5','/']
I have some code at the moment which loops through the characters in a string and tests them using re.match("\d") or ("\D"). I was wondering if there was a better way of doing this.
P.S: must be compatible with python 2.4
解决方案
Assuming the +
between 6 and 5 needs to be matched (which you're missing),
>>> import re
>>> s = '5 55+6+ 5/'
>>> re.findall(r'\d+|[^\d\s]+', s)
['5', '55', '+', '6', '+', '5', '/']
这篇关于如何根据数字/非数字拆分字符串(使用正则表达式?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文