校招时,百度二面的时候,让我写一个删除代码中的注释的代码,当时卡壳了。时隔一年多,想起这个问题,现在把这个写下来。
先说一下代码的思想,首先将“字符串”进行替换,替换成 uuid ,并且把字符串的内容存起来。_map是作为字典,uuid作为key,字符串内容作为value。
然后再把// 和 /**/ 进行替换
最后输出到文件中
import re
import uuid
fdr = open("input.c", 'r')
fdw = open("output.c", 'w')
_map = { }
outstring = ''
line = fdr.readline()
while line:
while True:
#这里要注意,我用的是re.S 比如print("aaa\n")
m = re.compile('\".*\"', re.S)
_str = m.search( line )
#如果没匹配成功,就合并,然后下一行
if None == _str:
outstring += line
break
key = str( uuid.uuid1() )
#
m = re.compile('\".*\"', re.S)
outtmp = re.sub(m, key, line, 1)
line = outtmp
_map[ key ] = _str.group(0)
line = fdr.readline()
m = re.compile(r'//.*')
outtmp = re.sub(m, ' ', outstring)
outstring = outtmp
m = re.compile(r'/\*.*?\*/', re.S)
outtmp = re.sub(m, ' ', outstring)
outstring = outtmp
for key in _map.keys():
outstring = outstring.replace(key, _map[key])
fdw.write(outstring)
fdw.close()