Python替换使用正则表达式

时间:2012-02-08 11:27:34

标签: python regex

有没有人知道如何用'\ r \ _< \ d +'替换所有出现的'< \ d +'正则表达式,例如

"<20"

应该转换为

"\r\n<20"

但是

"> HELLO < asassdsa"

shuld不受影响

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:3)

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

或使用前瞻:

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