使用Python和Regex替换字符串的特殊情况

时间:2013-08-28 09:57:23

标签: python regex

我想在一个内容中替换小数点而不是句点。

例如:

原创内容:

This is a cake. It is 1.45 dollars and 2.38 kg.

替换内容:

This is a cake. It cost 1<replace>45 dollars and 2<replace>38 kg.

如何使用Python Regex进行操作?

非常感谢。

1 个答案:

答案 0 :(得分:3)

re.sub与外观断言一起使用:

>>> import re
>>> s = 'This is a cake. It is 1.45 dollars and 2.38 kg.'
>>> re.sub(r'(?<=\d)\.(?=\d)', '<replace>', s)
'This is a cake. It is 1<replace>45 dollars and 2<replace>38 kg.'