【发布时间】:2010-12-09 18:12:25
【问题描述】:
我写了一个从 C++ 源文件中删除单行 cmets 的方法:
def stripRegularComments(text) {
def builder = new StringBuilder()
text.eachLine {
def singleCommentPos = it.indexOf("//")
def process = true
if(singleCommentPos > -1)
{
def counter = 0
it.eachWithIndex
{ obj,i ->
if((obj == '\'') || (obj == '"'))
counter++
if(i == singleCommentPos)
{
process = ((counter % 2) == 1)
if(!process)
return
}
}
if(!process)
{
def line = it.substring(0,singleCommentPos)
builder << line << "\n"
}
else
{
builder << it << "\n"
}
}
else
{
builder << it << "\n"
}
}
return builder.toString()
}
我测试了它:
println a.stripRegularComments("""
this is a test inside double quotes "//inside double quotes"
this is a test inside single quotes '//inside single quotes'
two// a comment?//other
single //comment
""")
它产生这个输出:
这是双引号内的测试“//双引号内” 这是单引号内的测试'//单引号内' 二 单身的是否有一些我遗漏的案例?
【问题讨论】:
-
这些是 C++ cmets。 C 使用
/*和*/来分隔注释部分。 -
我已经编辑了这个问题。谢谢!
-
只是小费;你可能想看看正则表达式
-
当您查看正则表达式时,请查看 Perl。在创建文本操作脚本时,Perl 非常强大且简单。
-
我只是想知道您为什么要从源代码中删除 cmets。这似乎不是一个好主意。我的意思是我认为我们都同意源中的 cmets 是一件好事,应该受到鼓励。
标签: c++ groovy comments header