python - 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
我的问题:使用正则表达式搜索和仅用句点替换以整数/数字为界的逗号而不破坏其他适当的逗号和句点的正确方法是什么?
提前感谢您提供的任何帮助。
解决方案
您可以使用
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])
模式永远不会匹配(,
匹配,然后引擎尝试确保,
是一个数字,这是错误的)。
推荐阅读
- c - Why is my pointer array returning a character in unicode?
- python-3.x - Python3. How to optimize decorator for handling exceptions?
- search - Using sed to find a string and replace that line but ignore commented out lines
- python - Schdeuling jobs after calling .start() APscheduler
- python-3.x - why my write statement is not working for a txt fie
- applescript-objc - Animated Image with Applescript
- matplotlib - removing all white margins from plt.show() when trying do show an image
- javascript - 如何使用 echo 语句访问 javascript 中的 php 变量
- java - Loop through HashSet of Objects Java
- f#-fake - 假构建无法获得所需的 Zip 文件结构