Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex - replace newline (\n) to something else

Tags:

python

regex

I'm trying to convert multiple continuous newline characters followed by a Capital Letter to "____" so that I can parse them.

For example,

i = "Inc\n\nContact"
i = re.sub(r'([\n]+)([A-Z])+', r"____\2", i) 

In [25]: i
Out [25]: 'Inc____Contact'

This string works fine. I can parse them using ____ later.

However it doesn't work on this particular string.

i =  "(2 months)\n\nML"
i = re.sub(r'([\n]+)([A-Z])+', r"____\2", i)

Out [31]: '(2 months)____L'

It ate capital M. What am I missing here?

like image 214
aerin Avatar asked Sep 15 '26 12:09

aerin


1 Answers

EDIT To replace multiple continuous newline characters (\n) to ____, this should do:

>>> import re
>>> i =  "(2 months)\n\nML"
>>> re.sub(r'(\n+)(?=[A-Z])', r'____', i)
'(2 months)____ML'

(?=[A-Z]) is to assert "newline characters followed by Capital Letter". REGEX DEMO.

like image 102
Quinn Avatar answered Sep 17 '26 01:09

Quinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!