我编写了一个从C ++源文件中删除单行注释的方法:
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()
}
我测试了它:
if(!process)
{
def line = it.substring(0,singleCommentPos)
builder << line << "\n"
}
else
{
builder << it << "\n"
}
它产生这个输出:
this is a test inside double quotes "//inside double quotes" this is a test inside single quotes '//inside single quotes' two single
是否有一些我遗失的案例?
答案 0 :(得分:11)
有趣的是trigraphs和续行。我个人最喜欢的是:
/??/
* this is a comment *??/
/
答案 1 :(得分:10)
// Single line comments can\
actually be multi line.
答案 2 :(得分:6)
我认为你无法处理
puts("Test \
// not a comment");
这也可能会产生问题:
puts("'"); // this is a comment
答案 3 :(得分:5)
您似乎无法处理转义引号,例如:
"Comment\"//also inside string"
与
"Comment"//not inside string"
答案 4 :(得分:2)
我认为你错过了/* comment */
案例。
答案 5 :(得分:1)
行尾的\
字符处理是在早期翻译阶段(阶段2)执行,而不是替换评论(阶段3)。因此,//
注释实际上可以占用原始源文件中的多行
// This \
whole thing \
is actually \
a single comment
P.S。哦......我看到这已经发布了。好的,我只是为了提及翻译阶段而保持活着:)
答案 6 :(得分:-1)
这总是最受欢迎的:
// Why doesn't this run?????????????????????/
foo(bar);