2

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
John Barton
  • 1,581
  • 4
  • 25
  • 51

1 Answers1

6

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563