How to replace newlines and maintain the surrounding text

Using regular expression groups, we can instruct whatever software we happen to be using what we want to replace. For example assuming we want to replace all newlines followed by a digit, we can use what is below in Textpad…

…while keeping the newline for those lines that are not followed by a digit.

You can do something similar in python with the following…

>> import re
>>> s="steve\n01\nbec\nky"
>>> print s
steve
01
bec
ky
>>> t = re.sub(r'\n+([0-9].*)',r' \1',s)
>>> print t
steve 01
bec
ky
>>>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.