mnowotka
mnowotka

Reputation: 17228

Python replace using 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

Upvotes: 6

Views: 16378

Answers (2)

Niklas B.
Niklas B.

Reputation: 95298

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)

Upvotes: 3

codaddict
codaddict

Reputation: 454960

>>> import re
>>> str = "<20"
>>> output = re.sub(r'<(?=\d)', r'\r\n<', str)
>>> output
'\r\n<20'

Upvotes: 10

Related Questions