2012-09-17 49 views
1

我需要一個Ruby的正則表達式來查找C指令之前的註釋。正則表達式來查找C評論

例如,我有這個文件example.c

/* 
* COMMENT NUMBER 1 
*/ 
x = rb_define_class_under (foo, "MyClassName1", bar); 

/* 
* COMMENT NUMBER 2 
*/ 
y = rb_define_class_under (foo, "MyClassName2", bar); 

/* 
* COMMENT NUMBER 3 
*/ 
z = rb_define_class_under (foo, "MyClassName3", bar); 

然後,我有我的紅寶石parser.rb解析器是這樣的:

content = File.open('example.c').read 

if content =~ /((?>\/\*.*?\*\/))([\w\.\s]+\s=\s)?rb_define_class_under.*?"(MyClassName1)"/m 
    puts "Comment number 1 is:" 
    puts $1 
end 

if content =~ /((?>\/\*.*?\*\/))([\w\.\s]+\s=\s)?rb_define_class_under.*?"(MyClassName2)"/m 
    puts "Comment number 2 is:" 
    puts $1 
end 

if content =~ /((?>\/\*.*?\*\/))([\w\.\s]+\s=\s)?rb_define_class_under.*?"(MyClassName3)"/m 
    puts "Comment number 3 is:" 
    puts $1 
end 

現在我期待的輸出是這樣的:

Comment number 1 is: 
/* 
* COMMENT NUMBER 1 
*/ 
Comment number 2 is: 
/* 
* COMMENT NUMBER 2 
*/ 
Comment number 3 is: 
/* 
* COMMENT NUMBER 3 
*/ 

但我得到:

Comment number 1 is: 
/* 
* COMMENT NUMBER 1 
*/ 
Comment number 2 is: 
/* 
* COMMENT NUMBER 1 
*/ 
Comment number 3 is: 
/* 
* COMMENT NUMBER 1 
*/ 

有什麼想法?什麼是正確的正則表達式來獲得預期的輸出?

回答

2

嘗試將.*添加到正則表達式的開頭。

目前.*?在您的正則表達式中rb_define_class_under之後會導致您始終匹配並捕獲字符串的第一部分,並且.*?會匹配,直到您實際查找的類名爲止。

通過在正則表達式開頭添加一個貪婪的匹配,確保您只在需要的類名前面的最後一個/*處啓動捕獲組。

例子:http://www.rubular.com/r/Orja089zAI

注意,您還是從字符串的開頭匹配,但第一個捕獲組是正確的註釋。