【发布时间】:2011-05-03 05:21:43
【问题描述】:
我整天都在做这个,我想不通。我在下面的字符串中有一些 Ruby 代码,并且只想将行与上面的代码以及代码的第一个注释(如果存在)进行匹配。
# Some ignored comment.
1 + 1 # Simple math (this comment would be collected) # ignored
# ignored
user = User.new
user.name = "Ryan" # Setting an attribute # Another ignored comment
这将捕获:
-
"1 + 1""Simple math"
-
"user = User.new"nil
-
"user.name = "Ryan""Setting an attribute"
我使用/^\x20*(.+)\x20*(#\x20*.+\x20*){1}$/ 匹配每一行,但它似乎不适用于所有代码。
【问题讨论】:
-
我不了解 Ruby,但我很确定
# Simple math (this comment would be collected) # ignored只是一条评论,而不是两条。第二个#被逐字处理,因为它已经被第一个#注释掉了。 -
我知道,这就是我需要的功能。
-
这可能是极难做到的。考虑像
user = "We're #1 \" #_# " # comment这样的行,更不用说内联 cmets(如i = 1 + /*comment */ 1,如果 ruby 有这些)。如果您需要强大的功能,请使用解析器(尽管可能会忽略换行)。 -
我有一个解决方案。我正在使用一个可以输出代码块源代码的库。我可以在没有 cmets 和 cmets 的情况下输出源代码,因此我可以删除所有不是注释的内容。