gpt4 book ai didi

python - 插入空格以分隔连接的字母和数字字符串 - Python RegEx

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:10 25 4
gpt4 key购买 nike

在 Python 中,我需要创建一个正则表达式,在任何串联的 AlphaNum 组合之间插入一个空格。例如,这就是我想要的:

8min15sec ==> 8 min 15 sec
7m12s ==> 7 m 12 s
15mi25s ==> 15 mi 25 s

RegEx101 demo

我在网上找到了解决方案,但它们有点太复杂了,我无法解析/修改。例如,我有这个:

[a-zA-Z][a-zA-Z\d]*

但它只识别第一个插入点:8Xmin15sec(X)

还有这个

(?<=[a-z])(?=[A-Z0-9])|(?<=[0-9])(?=[A-Z])

但它只找到这个点:8minX15sec (the X)

我可以肯定地使用具有完整语法的手来查找每个插入点并插入空格。

RegEx101 demo (与上面相同的链接)

最佳答案

下面的方法怎么样:

import re

for test in ['8min15sec', '7m12s', '15mi25s']:
print(re.sub(r'(\d+|\D+)', r'\1 ', test).strip())

这会给你:

8 min 15 sec 
7 m 12 s
15 mi 25 s

关于python - 插入空格以分隔连接的字母和数字字符串 - Python RegEx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com