我有一个字符串,其中 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

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

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

最佳答案

您可以使用

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

请参阅 Python online demo

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

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

10-07 14:06
查看更多