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
*/
有什麼想法?什麼是正確的正則表達式來獲得預期的輸出?