ruby - 为什么只有有限数量的正则表达式捕获存储在 `global_variables` 中?

标签 ruby regex pseudo-globals

如果我用包含十个捕获的正则表达式进行匹配:

/(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/

相关文章:

ruby - 为什么 Ruby 全局字符串(如 $&)会无误地忽略突变?

ruby - 带有 Fixnum 和 Symbol 的 mutator 方法

python - 正则表达式无法排除带有换行符的匹配项

java - 如何使用分隔字符串 "#|#"分割字符串

java - 计算字符串中的单词数

ruby - 如何使用 '$MATCH' 作为 '$&' 的别名

ruby - 基于条件的 Rspec 测试

ruby - 为什么 Ruby 需要所有相似的属性来进行排序?

ruby-on-rails - Rails,在尝试使用 put http 方法的表单中出现问题

ruby - 如何覆盖 `File::SEPARATOR`