6

Does anyone know how to replace all ocurences of '<\d+' regex with '\r\n<\d+', for example

"<20" 

should be transformed to

"\r\n<20" 

but

"> HELLO < asassdsa" 

shuld be untouched

2 Answers 2

10
>>> import re >>> str = "<20" >>> output = re.sub(r'<(?=\d)', r'\r\n<', str) >>> output '\r\n<20' 
Sign up to request clarification or add additional context in comments.

2 Comments

Why not go all the way and put the entire regex into the lookahead?
@Tim: That's what I thought. Also, maybe we shouldn't encourage the use of str as a variable name, although I always fail to find a better name :(
3
import re def replace(value): return re.sub(r'(<\d)', r'\r\n\1', value) 

Or using lookahead:

import re def replace(value): return re.sub(r'(?=<\d)', r'\r\n', value) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.