我一整天都在做这个,但我无法弄清楚。我在下面的字符串中有一些 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}$/
与每一行匹配,但它似乎并不适用于所有代码。
科比的答案部分有效,但与末尾缺少注释的代码行不匹配。
当遇到字符串插值时也会失败,例如:
str = "My name is #{first_name} #{last_name}" # first comment
...将被错误地匹配为:str = "My name is #{first_name}
您需要更全面的正则表达式。这是一个想法:
/^[\t ]*([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)(#([^#\r\n]*))?/
-
^[\t ]*
- 前导空白。
-
([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)
- Matches a line of code.
Breakdown:
-
[^#"'\r\n]
- 一行代码中的第一个字符,并且...
-
"(\\"|[^"])*"
- 双引号字符串,或者...
-
'(\\'|[^'])*'
- 单引号字符串,或者...
-
[^#\n\r]
- 引用字符串之外的任何其他字符,但不是#
或行结尾。
-
(#([^#\r\n]*))?
- 匹配代码行末尾的第一个注释(如果有)。
由于逻辑更复杂,这将为每个匹配捕获 6 个子模式。子模式 1 是代码,子模式 6 是注释,其他的可以忽略。
给出以下代码块:
# Some ignored comment.
1 + 1 # Simple math (this comment would be collected) # ignored
# ignored
user = User.new
user.name = "Ryan #{last_name}" # Setting an attribute # Another ignored comment
上述正则表达式将生成以下内容(为简洁起见,我排除了子模式 2、3、4、5):
-
1. 1 + 1
6. Simple math (this comment would be collected)
-
1. user = User.new
6.
-
1. user.name = "Ryan #{last_name}"
6. Setting an attribute
Demo: http://rubular.com/r/yKxEazjNPC http://rubular.com/r/yKxEazjNPC
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)