gpt4 book ai didi

python - 正则表达式:在数字后跟字母时添加空格

转载 作者:行者123 更新时间:2023-12-01 00:09:32 28 4
gpt4 key购买 nike

在一组数字之后,我想在字符串中添加一个空格。例如,以下字符串应在数字后添加空格:

Before                           After
"0ABCD TECHNOLOGIES SERVICES" "0 ABCD TECHNOLOGIES SERVICES"
"ABCD0 TECHNOLOGIES SERVICES" "ABCD 0 TECHNOLOGIES SERVICES"

"ABCD 0TECHNOLOGIES SERVICES" "ABCD 0 TECHNOLOGIES SERVICES"
"ABCD TECHNOLOGIES0 SERVICES" "ABCD TECHNOLOGIES 0 SERVICES"

"ABCD TECHNOLOGIES 0SERVICES" "ABCD TECHNOLOGIES 0 SERVICES"
"ABCD TECHNOLOGIES SERVICES0" "ABCD TECHNOLOGIES SERVICES 0"

我一直在尝试使用 Python 中的正则表达式,如下所示:

text= re.sub(r'([0-9]+)?([A-Za-z]+)?([0-9]+)?',
r'\1 \2 \3',
text,
0,
re.IGNORECASE)

使用前面的代码,我得到了不想要的空格,这会影响其他正则表达式转换:

"0 abcd     technologies     services   "

如何在字符串中添加空格而不添加不需要的空格?

最佳答案

您可以使用

re.sub(r'(?<=\d)(?=[^\d\s])|(?<=[^\d\s])(?=\d)', ' ', text)

请参阅regex demo .

图案详细信息

  • (?<=\d)(?=[^\d\s]) - 数字和字符之间的位置(数字和空格除外)
  • | - 或
  • (?<=[^\d\s])(?=\d) - 数字以外的字符与空格和数字之间的位置。

Python test :

import re
tests = ['0ABCD TECHNOLOGIES SERVICES',
'ABCD0 TECHNOLOGIES SERVICES',
'ABCD 0TECHNOLOGIES SERVICES',
'ABCD TECHNOLOGIES0 SERVICES',
'ABCD TECHNOLOGIES 0SERVICES',
'ABCD TECHNOLOGIES SERVICES0']

rx = re.compile(r'(?<=\d)(?=[^\d\s])|(?<=[^\d\s])(?=\d)')

for test in tests:
print(rx.sub(' ', test))

输出:

0 ABCD TECHNOLOGIES SERVICES
ABCD 0 TECHNOLOGIES SERVICES
ABCD 0 TECHNOLOGIES SERVICES
ABCD TECHNOLOGIES 0 SERVICES
ABCD TECHNOLOGIES 0 SERVICES
ABCD TECHNOLOGIES SERVICES 0

关于python - 正则表达式:在数字后跟字母时添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59724564/

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