Regex: Add space after a number when followed by letter

試著忘記壹切 提交于 2020-02-05 06:16:25

问题


Following a set of numbers I would like to add a space to the string. For instance, the following strings should add a space after a number:

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"

I have been trying to work on regex in Python as in the following way:

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

With the previous code I am getting undesired spaces which are affecting other regex transformation:

"0 abcd     technologies     services   "

How can I get the addition of space in the string without adding undesired spaces?

Thanks for your guide :)


回答1:


You may use

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

See the regex demo.

Pattern details

  • (?<=\d)(?=[^\d\s]) - a location between a digit and a char other than a digit and whitespace
  • | - or
  • (?<=[^\d\s])(?=\d) - a location between a char other than a digit and whitespace and a digit.

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))

Output:

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


来源:https://stackoverflow.com/questions/59724564/regex-add-space-after-a-number-when-followed-by-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!