Re: [问题] 请问怎么找出注解

楼主: ccbruce (今、そこに いる仆)   2012-08-15 17:28:27
※ 引述《PurpleCrow (阿乐)》之铭言:
: ※ 引述《ccbruce (今、そこに いる仆)》之铭言:
: : 我是用.net的Regex的
: : 现在想要写一个可以删掉所有C/C++ Style comment的程式
: : 而且不可以删掉包在双引号内的类似注解的字串
: : 现在用的pattern为:
: : (?!")((//.*)|((?s)(/\*.*?\*/)))(?<!")
: : 虽然可以找出单行跟多行注解, 不过包在字串里的类似注解的字串也一起被找出来了
: : 请问有什么解决的方法吗?
: : 正常:
: : //comment
: : "aaa" //comment
: : /*
: : comment
: : */
: : "aaa" /*
: : comment
: : */
: : 异常:
: : "//not comment"
: : "/*not comment"
: 总算看懂了
: 编号一下
: //comment1
: "aaa" //comment2
: /*
: comment3
: */
: "aaa" /*
: comment4
: */
: "//not comment5"
: "/*not comment6"
: (?<!")(//[^\n]+|/\*.*?\*/)
: 得
: //comment1
: //comment2
: /*
: comment3
: */
: /*
: comment4
: */
: 是这个意思吗?
我的意思是, 用以下的内容去测我的pattern
//comment
"aaa" //comment
/*
comment
*/
"aaa" /*
comment
*/
"//not comment"
"/*not comment*/"
结果是, 不论红字还是蓝字, 都被砍光了。因为它们都被match到了。
那么, 要怎么修改pattern才能让我的程式不会砍到蓝字部份呢?
因为没办法用上面的pattern来找出正确的注解, 所以现在的作法很糟, 如以下程式码:
先找出所有的字串跟注解, 然后一块块去看, 只要是字串就跳过, 注解才取代。
String^ newline_evaluator(Match^ m)
{
String ^ret=L"";
IEnumerator ^e=m->Value->GetEnumerator();
while(e->MoveNext())
{
Char ^ch=(Char ^)e->Current;
if(!ch->CompareTo(L'\n'))
ret+=L'\n';
}
return ret;
}
String^ passstr_evaluator(Match^ m)
{
if(m->Value[0]==L'\"')
return m->Value;
return newline_evaluator(m);
}
...
...
...
String ^raw=nullptr;
MatchEvaluator ^peval=gcnew MatchEvaluator(passstr_evaluator);
...
...
...
raw=Regex::Replace(raw,
L"(?s)\"[^\"]*\"|(?-s)//.*|(?s)/\\*.*?\\*/",
peval);
作者: PurpleCrow (17868)   2012-08-15 19:08:00
我的pattern不是没选到蓝字部分吗? @ @

Links booklink

Contact Us: admin [ a t ] ucptt.com