简体   繁体   中英

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

>>> import re
>>> str = "<20"
>>> output = re.sub(r'<(?=\d)', r'\r\n<', str)
>>> output
'\r\n<20'
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM