正则表达式匹配包含两条连续的数字和字母的“单词”或反之亦然,并将其拆分

2024-04-24 07:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下一行文字,如下所示:

text= 'Cms12345678 Gleandaleacademy Fee Collection 00001234Abcd Renewal 123Acgf456789'

我正试图拆分numbers followed by characterscharacters 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的最后一个元素。
请帮助我获得正确的输出


1条回答
网友
1楼 · 发布于 2024-04-24 07:26:46

你可以用

re.sub(r'\b(?:([a-zA-Z]+)(\d+)|(\d+)([a-zA-Z]+))\b', r'\1\3 \2\4', text)

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

import re
text = "Cms1291682971 Gleandaleacademy Fee Collecti 0000548Andb Renewal 402Ecfev845410001"
print( re.sub(r'\b(?:([a-zA-Z]+)(\d+)|(\d+)([a-zA-Z]+))\b', r'\1\3 \2\4', text) )
# => Cms 1291682971 Gleandaleacademy Fee Collecti 0000548 Andb Renewal 402Ecfev845410001

相关问题 更多 >