Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace using regex

Tags:

python

regex

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

like image 577
mnowotka Avatar asked Feb 08 '12 11:02

mnowotka


2 Answers

>>> import re
>>> str = "<20"
>>> output = re.sub(r'<(?=\d)', r'\r\n<', str)
>>> output
'\r\n<20'
like image 121
codaddict Avatar answered Sep 21 '22 10:09

codaddict


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)
like image 37
Niklas B. Avatar answered Sep 20 '22 10:09

Niklas B.