简体   繁体   中英

In vim, how to remove all the C and C++ comments?

How to remove all C and C++ comments in vi?

//

/*       
 */

You can't. Parsing C and C++ comments is not something that regular expressions can do. It might work for simple cases, but you never know if the result leaves you with a corrupted source file. Eg what happens to this:

 printf ("//\n");

The proper way is to use an external tool able to parse C. For example some compilers may have an option to strip comments.

Writing a comment stripper is also a basic exercise in lex and yacc programming.

See also this question: Remove comments from C/C++ code

With regular expressions, because of the complexity of C/C++ syntax, you will at best achieve a solution that is 90% correct. Better let the right tool (a compiler) do the job.

Fortunately, Vim integrates nicely with external tools. Based on this answer , you can do:

:%! gcc -fpreprocessed -dD -E "%" 2>/dev/null

Caveats:

  • requires gcc
  • it also slightly modifies the formatting (shrunk indent etc.)
Esc:%s/\/\///

Esc:%s/\/\*//

Esc:%s/\*\///

You can use a lexical analyzer like Flex directly applied to source codes. In its manual you can find " How can I match C-style comments? ".

If you need an in-depth tutorial, you can find it here ; under "Lexical Analysis" section you can find a pdf that introduce you to the tool and an archive with some practical examples, including "c99-comment-eater".

这是一个vim内联函数,可删除当前缓冲区中的所有C和C ++注释。

keepp %s/\%(\/\*\_.\{-}\*\/\)\|\/\/.*//

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM