我有以下一行文字,如下所示:
text= 'Cms12345678 Gleandaleacademy Fee Collection 00001234Abcd Renewal 123Acgf456789'
我正试图拆分numbers followed by characters
或characters followed by numbers
以获得以下输出:
output_text = 'Cms 12345678 Gleandaleacademy Fee Collection 00001234 Abcd Renewal 123Acgf456789
我尝试了以下方法:
import re
text = 'Cms12345678 Gleandaleacademy Fee Collection 00001234Abcd Renewal 123Acgf456789'
text = text.lower().strip()
text = text.split(' ')
output_text =[]
for i in text:
if bool(re.match(r'[a-z]+\d+|\d+\w+',i, re.IGNORECASE))==True:
out_split = re.split('(\d+)',i)
for j in out_split:
output_text.append(j)
else:
output_text.append(i)
output_text = ' '.join(output_text)
其输出为:
output_text = 'cms 12345678 gleandaleacademy fee collection 00001234 abcd renewal 123 acgf 456789 '
由于re.match
中的正则表达式不正确,此代码也正在剥离文本123acgf456789
的最后一个元素。
请帮助我获得正确的输出
你可以用
见regex demo
详细信息
\b
-字边界(?:
-非捕获组的开始(将单词边界应用于所有备选词所必需的):([a-zA-Z]+)(\d+)
-第1组:一个或多个字母,第2组:一个或多个数字|
-或(\d+)([a-zA-Z]+)
-第3组:一个或多个数字,第4组:一个或多个字母)
-组结束\b
-字边界在替换过程中,
\1
和\2
或\3
和\4
{a2}被初始化,因此将它们连接为\1\3
和\2\4
会产生正确的结果见a Python demo:
相关问题 更多 >
编程相关推荐