首页 > 解决方案 > python中的正则表达式用句点替换以整数为界的逗号

问题描述

我有一个字符串,其中 IP 地址中有一个错误的逗号 (','),它应该只是一个句点 ('.')。整个字符串是:

a = 'This is a test, which uses commas for a bad IP Address. 54.128,5,5, 4.'

在上面的字符串中,IP 地址54.128,5,5应该是54.128.5.5

我尝试使用re.sub(),如下,但它似乎不起作用...

def stripBadCommas(string):
  newString = re.sub(r'/(?<=[0-9]),(?<=[0-9])/i', '.', string)
  return newString

a = 'This is a test, which uses commas for a bad IP Address. 54.128,5,5, 4.'
b = ''
b = stripBadCommas(a)
print a
print b

我的问题:使用正则表达式搜索和仅用句点替换以整数/数字为界的逗号而不破坏其他适当的逗号和句点的正确方法是什么?

提前感谢您提供的任何帮助。

标签: pythonregexreplacesubstitution

解决方案


您可以使用

def stripBadCommas(s):
  newString = re.sub(r'(?<=[0-9]),(?=[0-9])', '.', s)
  return newString

请参阅Python 在线演示

请注意,Pythonre模式不是使用正则表达式文字符号编写的,/and/i被视为模式的一部分。此外,该模式不需要不区分大小写的修饰符,因为它内部没有字母(不匹配大小写字母)。

此外,您使用了第二个lookbehind (?<=[0-9]),而必须有一个肯定的lookahead (?=[0-9]),因为,(?<=[0-9])模式永远不会匹配(,匹配,然后引擎尝试确保,是一个数字,这是错误的)。


推荐阅读