如果我用包含十个捕获的正则表达式进行匹配:
/(o)(t)(th)(f)(fi)(s)(se)(e)(n)(t)/.match("otthffisseent")
然后,对于 $10
,我得到:
$10 # => "t"
但 global_variables
中缺少它。我得到(在 irb session 中):
[:$;, :$-F, :$@, :$!, :$SAFE, :$~, :$&, :$`, :$', :$+, :$=, :$KCODE, :$-K, :$,,
:$/, :$-0, :$\, :$_, :$stdin, :$stdout, :$stderr, :$>, :$<, :$., :$FILENAME,
:$-i, :$*, :$?, :$$, :$:, :$-I, :$LOAD_PATH, :$", :$LOADED_FEATURES,
:$VERBOSE, :$-v, :$-w, :$-W, :$DEBUG, :$-d, :$0, :$PROGRAM_NAME, :$-p, :$-l,
:$-a, :$binding, :$1, :$2, :$3, :$4, :$5, :$6, :$7, :$8, :$9]
这里只列出前九个:
$1, :$2, :$3, :$4, :$5, :$6, :$7, :$8, :$9
这也得到了证实:
global_variables.include?(:$10) # => false
$10
存储在哪里,为什么不存储在 global_variables
中?
最佳答案
Ruby 似乎在解析器级别处理 $1
、$2
等:
ruby --dump parsetree_with_comment -e '$100'
输出:
###########################################################
## Do NOT use this node dump for any purpose other than ##
## debug and research. Compatibility is not guaranteed. ##
###########################################################
# @ NODE_SCOPE (line: 1)
# | # new scope
# | # format: [nd_tbl]: local table, [nd_args]: arguments, [nd_body]: body
# +- nd_tbl (local table): (empty)
# +- nd_args (arguments):
# | (null node)
# +- nd_body (body):
# @ NODE_NTH_REF (line: 1)
# | # nth special variable reference
# | # format: $[nd_nth]
# | # example: $1, $2, ..
# +- nd_nth (variable): $100
顺便说一句,maximum number of capture groups是 32,767,您可以通过 $n
访问所有内容:
/#{'()' * 32768}/ #=> RegexpError: too many capture groups are specified
/#{'()' * 32767}/ =~ '' #=> 0
defined? $32767 #=> "global-variable"
$32767 #=> ""
关于ruby - 为什么只有有限数量的正则表达式捕获存储在 `global_variables` 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691743/