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