Skip to content Skip to sidebar Skip to footer

How To Insert Space Between Alphabet Characters And Numeric Character Using Regex?

I'm trying to insert space between numeric characters and alphabet character so I can convert numeric character to words like : Input : subject101 street45 Output :

Solution 1:

Try this Regex:

(?i)(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)

Click for Demo

Replace each match with a space

Explanation:

  • (?i) - modifier to make the matches case-insensitive
  • (?<=\d)(?=[a-z]) - finds the position just preceded by a digit and followed by a letter
  • | - OR
  • (?<=[a-z])(?=\d) - finds the position just preceded by a letter and followed by a digit

Code output

import re
regex = r"(?i)(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)"
test_str = ("subject101\n""     street45")
subst = " "
result = re.sub(regex, subst, test_str, 0)
if result:
    print (result)

Solution 2:

You can use if statement (?(#group)) in regex to check if char is digit or a letter.

Regex: (?<=([a-z])|\d)(?=(?(1)\d|[a-z]))

Python code:

defaddSpace(text):
    return re.sub(r'(?<=([a-z])|\d)(?=(?(1)\d|[a-z]))', ' ', text)

Output:

addSpace('subject101')
>>> subject 101
addSpace('101subject')
>>> 101 subject

Solution 3:

A way to do this would be to pass a callable to re.sub. This allows you to reuse the matched substring to generate the replacement value.

subject = '101subject101'

s = re.sub(r'[a-zA-Z]\d|\d[a-zA-Z]', lambda m: ' '.join(m.group()), subject )
# s: '101 subject 101'

Post a Comment for "How To Insert Space Between Alphabet Characters And Numeric Character Using Regex?"