python 中的正则表达式用句点替换以整数为界的逗号
Regular expression in python to substitute commas bounded by whole numbers with periods
我有一个字符串,其中 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
我的问题:使用正则表达式搜索和仅替换由整个 numbers/numerics 限定的逗号而不破坏句号的正确方法是什么其他合适的逗号和句点?
提前感谢您提供的任何帮助。
您可以使用
def stripBadCommas(s):
newString = re.sub(r'(?<=[0-9]),(?=[0-9])', '.', s)
return newString
请注意,Python re
模式不是使用正则表达式文字符号编写的,/
和 /i
被视为模式的一部分。此外,该模式不需要不区分大小写的修饰符,因为它内部没有字母(不匹配大小写字母)。
此外,您使用了第二个后向 (?<=[0-9])
而必须有一个正向前向 (?=[0-9])
因为 ,(?<=[0-9])
模式从不匹配(匹配 ,
然后引擎试图确保 ,
是一个数字,这是错误的)。
我有一个字符串,其中 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
我的问题:使用正则表达式搜索和仅替换由整个 numbers/numerics 限定的逗号而不破坏句号的正确方法是什么其他合适的逗号和句点?
提前感谢您提供的任何帮助。
您可以使用
def stripBadCommas(s):
newString = re.sub(r'(?<=[0-9]),(?=[0-9])', '.', s)
return newString
请注意,Python re
模式不是使用正则表达式文字符号编写的,/
和 /i
被视为模式的一部分。此外,该模式不需要不区分大小写的修饰符,因为它内部没有字母(不匹配大小写字母)。
此外,您使用了第二个后向 (?<=[0-9])
而必须有一个正向前向 (?=[0-9])
因为 ,(?<=[0-9])
模式从不匹配(匹配 ,
然后引擎试图确保 ,
是一个数字,这是错误的)。