Skip to main content
 首页 » 编程设计

Python之替换部分 C 程序,但跳过注释

2025年04月02日16lonelyxmas

使用 Python 和正则表达式,我需要在 C 程序中的每个赋值运算符的任一侧添加一个空格,但在注释中跳过运算符:

int x; 
int y=100; 
x=y; 
// a=b+c 
/* i=j+k */ 

以上需要翻译成:

int x; 
int y = 100; 
x = y; 
// a=b+c 
/* i=j+k */ 

我试过使用这个正则表达式来跳过单行注释:

try: 
    source = re.sub(r'(?<!//)(.*)([^\s])=([^\s])', r'\1\2 = \3', source) 
except Exception as e: 
    pass 

但它不起作用。

感谢您的帮助。

请您参考如下方法:

你可以尝试这样做:

for line in open("file_to_be_formated.c"): 
    li=line.strip() 
    if not (li.startswith("//") or li.startswith("/*")): 
        # format code 

将跳过注释行的正则表达式如下:

(?://[^\n]*|/\*(?:(?!\*/).)*\*/) 

一个小例子:

import re 
 
my_string = """// my single line comment 
another random text 
/*some multi-line 
comment*/ 
""" 
 
m = re.findall(r'(?://[^\n]*|/\*(?:(?!\*/).)*\*/)', my_string, re.DOTALL) 
print(m) 

输出将是一个包含匹配评论的列表:

['// my single line comment', '/*some multi-line\ncomment*/']