Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace substring with newline in Python regex

I am trying to use regex in Python to replace a substring

import re    
sample_string1 = "This is a sample. Another sample sentence"

print (re.sub("This is a sample", ' ', sample_string1))

Output:

. Another sample sentence

But if there is a new line in between the string I want to replace, it does not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sample_string2 = "This is a \n sample. Another sample sentence"
print (re.sub("This is a sample", ' ', sample_string2))

Output:

This is a 
 sample. Another sample sentence

Expected Output:

 . Another sample sentence

I am trying to replace the input string with white space even if there are multiple new line characters in between.

I am able to replace it iteratively, but any suggestions on the regex will be helpful.

>Solution :

Here is a solution that captures all new lines or whitespaces between your input string.

sample_string2 = "This\n       is a \n sample   \n   . Another sample sentence"
print (re.sub("This[\n\s]*is[\n\s]*a[\n\s]*sample[\n\s]*", ' ', sample_string2))

Prints: . Another sample sentence

  • \n is new line
  • \s is whitespace
  • the asterisk (*) means 0 or more

All together: [\n\s]* means to capture 0 or more whitespaces or new lines

BE CAREFULL: This solution will apply only for this input string. It doesn’t work dynamically for other strings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading