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

标签 python regex

使用 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*/']

关于Python - 替换部分 C 程序,但跳过注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36270756/

相关文章:

Python 的 `unittest` 缺少 `assertHasAttr` 方法,我应该用什么代替?

python - 如何在不变的 URL 中抓取不同城市的多个页面 - Python 3

python - lxml findall() 问题

regex - Grep 和正则表达式 : inconsistent behaviour

c - 在 C 中解析 iCalendar 文件

php - 正则表达式:替换两个字符之间的字符

python - 分页在 DRF APIView 中不起作用

python - 如何在确保向前兼容性的同时保存 Gensim 模型?

javascript - JSLint - 带变量的正则表达式的错误转义

javascript - 正则表达式查找字符串中不匹配的单词