Regular Expressions 101

Community Patterns

Add spaces between words and punctuation

0

Regular Expression
Python

r"
([a-zA-z0-9 ]+)|([?,.!:\'\"=_\-%#@\&\])([a-zA-z0-9 ]|$)
"
g

Description

Use this twice, and then apply another regex to make this work properly:

import re
line = 'your text here'
line = re.sub(r'([a-zA-z0-9 ])([?,.!:\'\"])([a-zA-z0-9 ]|$)', r'\1 \2 \3', line)
line = re.sub(r'([a-zA-z0-9 ])([?,.!:\'\"])([a-zA-z0-9 ]|$)', r'\1 \2 \3', line)
line = re.sub(r'[ ]+', ' ', line)
print(line)
Submitted by toiletsandpaper - a year ago