使用 re.split() 拆分多个值的字符串

string splitting with multiple values using re.split()

我有一个字符串: "2y20w2d2h2m2s" 我需要把它拆分成这样: ["2y","20w","2d","2h","2m"2s”] 我尝试使用 re.split 但我无法让它工作 这是我的尝试: time = re.split("s m h d w y", time) *时间是上面的字符串 最后,我会感谢你帮助理解如何让它工作

如果您希望将字符串拆分成的部分总是以 2 开头,则可以这样做:

string = "2y20w2d2h2m2s"

print(string.replace('2', ' 2').split())

尝试:

import re

print(re.findall('(\d+[a-z])', "2y20w2d2h2m2s"))

输出

['2y', '20w', '2d', '2h', '2m', '2s']

说明

1 个或多个数字后跟一个字母的正则表达式模式

(\d+[a-z])

代码:

import re

time_str = "2y20w2d2h2m2s"
time = re.findall(r"(\d*\S)", time_str)
print(time)

输出:

>>> python3 test.py 
['2y', '20w', '2d', '2h', '2m', '2s']

在线试用:

针对您的用例尽可能具体:

import re
s = "2y20w2d2h2m2s"
re.findall('([0-9]{1,2}[ywdhms]{1})', s)

输出:['2y', '20w', '2d', '2h', '2m', '2s']

这会生成您想要的结果,没有多余的字母或超过两位数的数字。