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:
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.