I have a pattern of text that I would like to find and push to a new line. The pattern is ),
followed by a space and a character. Like this –
JavaScript
x
7
1
text_orig =
2
3
text cat dog cat dog
4
),
5
text rabbit cat dog
6
), text coffee cat dog. #need to indent this line
7
where it would become
JavaScript
1
8
1
text_new =
2
3
text cat dog cat dog
4
),
5
text rabbit cat dog
6
),
7
text coffee cat dog
8
I’m pretty close to a solution, but stuck on what approach to use. Currently, I’m using re.sub
but I believe that removes the first letter of the text like so –
JavaScript
1
8
1
text_new =
2
3
text cat dog cat dog
4
),
5
text rabbit cat dog
6
),
7
ext coffee cat dog # removes first letter
8
JavaScript
1
2
1
re.sub('),sw','), n',text_orig)
2
Would I need search
instead of sub
? Help is very appreciated
Advertisement
Answer
You can use
JavaScript
1
2
1
re.sub(r'),[^Sn]*(?=w)', '),n', text_orig)
2
See the regex demo.
Or, if the pattern should only match at the start of a line, you should add ^
and the re.M
flag:
JavaScript
1
2
1
re.sub(r'^),[^Sn]*(?=w)', '),n', text_orig, flags=re.M)
2
Here,
^
– start of a line (withre.M
flag)),
– a),
substring[^Sn]*
– zero or more whitespaces other than LF char(?=w)
– a positive lookahead that requires a word char immediately to the right of the current location.