使用Python重新发送带/ *的注释

时间:2013-07-11 09:05:47

标签: python regex

在我的C程序中,我应该用“/ * comment * /”

转换每个“// comment”

我用Python重新考虑了下面的代码,但是不知道如何

在行尾插入* /。

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

任何想法都会感激不尽。谢谢。

2 个答案:

答案 0 :(得分: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 */
}

答案 1 :(得分:1)

改编自在{J}中寻找单行注释的previous post,您可以使用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*/
    }
}