1

在我的 C 程序中,我应该将每个“// comment”转换为“/* comment */”

我用 Python re 想到了下面的代码,但不知道如何

在行尾插入 */ 之前。

regexp = re.compile(r'//', re.MULTILINE)
c = regexp.sub('/*',c)

任何想法将不胜感激。谢谢你。

4

2 回答 2

3

这是(IMO)“更好”解决方案的开始。它使用正则表达式扫描输入,不仅匹配单行注释,还匹配那些可以包含的标记//

#!/usr/bin/env python

import re
import sys

source = """
/* 
 * not 
// a single line 
// comment 
*/

// include stuff
#include<stdio.h>

main()
{
    // comments with a '*/' !
    printf("Again, no single // line comment"); // comment
}
"""

pattern = re.compile(r"""   (//([^\r\n]*)) # match a single line comment
                          | "[^"]*"        # match a string literal
                          | /\*.*?\*/      # match a multi line comment
                          | .              # fall through: match any char
                      """
                         , re.X | re.S)

print("%s" % source)              

print('=' * 40)

for match in pattern.finditer(source):
    if match.group(1):
        # we found a single line comment
        s = match.group(2).replace('*/', '* /')
        sys.stdout.write("/*" + s + " */")
    else:
        # something other than a single line comment, just print it
        sys.stdout.write(match.group())

这将打印:

/* 
 * not 
// a single line 
// comment 
*/

// include stuff
#include<stdio.h>

main()
{
    // comments with a '*/' !
    printf("Again, no single // line comment"); // comment
}

========================================

/* 
 * not 
// a single line 
// comment 
*/

/* include stuff */
#include<stdio.h>

main()
{
    /* comments with a '* /' ! */
    printf("Again, no single // line comment"); /* comment */
}
于 2013-07-11T09:59:23.053 回答
1

改编自之前在 Java 中寻找单行注释的帖子,您可以使用pyparsing

data = """
class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
        System.out.println("Hello World!"); // Nested //Print 'Hello World!'
        System.out.println("http://www.example.com"); // Another nested // Print a URL
        System.out.println("\"http://www.example.com"); // A nested escaped quote // Print another URL
    }
}"""

from pyparsing import *

dbls = QuotedString('"', '\\', '"')
sgls = QuotedString("'", '\\', "'")
strings = dbls | sgls
g = dblSlashComment.ignore(strings)
g.setParseAction(lambda L,: '/*' + L[0].lstrip('//') + '*/')
print g.transformString(data)

输出:

class HelloWorld {

    /* method main(): ALWAYS the APPLICATION entry point*/
    public static void main (String[] args) {
        System.out.println("Hello World!"); /* Nested //Print 'Hello World!'*/
        System.out.println("http://www.example.com"); /* Another nested // Print a URL*/
        System.out.println(""http://www.example.com"); /* A nested escaped quote // Print another URL*/
    }
}
于 2013-07-11T09:56:32.397 回答