I have a string as follows:
line = "This is a text.This is another text,it has no space after the comma."
I want to add a space after dots and commas, so that the end result is:
newline = "This is a text. This is another text, it has no space after the comma."
I tried the solution from here: Python Regex that adds space after dot, but it does work only for dots or commas. I have not been able to grasp how to get the regex recognize both characters at once.
Use this regex to match locations where preceding character is a dot or a comma and the next character isn't a space:
(?<=[.,])(?=[^\s])
(?<=[.,])
positive lookbehind that looks for dots or commas
(?=[^\s])
positive lookahead that matches anything that isn't a space
So this will match positions just after the comma or the space like ext.This
or text,it
. but not word. This
.
Replace with a single space ()
Regex101 Demo
Python:
line = "This is a text.This is another text,it has no space after the comma."
re.sub(r'(?<=[.,])(?=[^\s])', r' ', line)
// Output: 'This is a text. This is another text, it has no space after the comma.'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With