Ruby has special variables $ 1, $ 2, $ 3 ...
, and $ n
is assigned the value that matches the nth parenthesis in the last successful pattern match.
"abc" =~ /(.)(.)(.)/
p $1 #=> "a"
p $2 #=> "b"
p $3 #=> "c"
Number n You can use any number of large positive integers.
It says, but in reality, when I try to use a huge value, a warning is displayed (I noticed when playing)
$ ruby -e '$9999999999999999'
-e:1: warning: `$9999999999999999' is too big for a number variable, always nil
In this case, I am wondering how much value can be used as n of $ n
, so when I looked it up with the following code using a simple binary search, the maximum value seems to be 1073741823 in my environment. did.
require 'stringio'
ok = 0
ng = 10**10
while (ok-ng).abs > 1
io = StringIO.new
$stderr = io
mi = (ok+ng)/2
eval("$#{mi}")
if io.size == 0
ok = mi
else
ng = mi
end
$stderr = STDERR
end
p ok #=> 1073741823
Even if you check it by another method, it seems that you will be warned if $ 1073741823
is the maximum and the value is larger than that. However, the value 1073741823 seems to be environment-dependent, so depending on the environment, you may be able to use a larger value, or you may get a warning with a smaller value.
$ ruby -e '$1073741823'
#=>Nothing happens
$ ruby -e '$1073741824'
#=>A warning is output
#=> -e:1: warning: `$1073741824' is too big for a number variable, always nil
The obvious question is what happens if the match is successful with a regular expression that captures more than 1073741823, but that's okay. In Ruby, the upper limit of the number of captures is set to 32767, and regular expressions that exceed that limit will fail to compile.
$ ruby -e 'Regexp.compile("(.)"*32767)'
#=>Nothing happens
$ ruby -e 'Regexp.compile("(.)"*32768)'
#=>RegexpError occurs. The message is as follows
#=> `initialize': too many capture groups are specified:
I found the value 32767 with a simple script using the following binary search, but when I look at the source code of Onikumo, which is the regular expression engine of Ruby, I see the upper limit of the number of captures [ʻONIG_MAX_CAPTURE_GROUP_NUM. There is a variable to show, which seems to be 32767. ](Https://github.com/ruby/ruby/blob/c5eb24349a4535948514fe765c3ddb0628d81004/include/ruby/onigmo.h#L438), then the maximum value on the side of the special variable
$ 1, $ 2, $ 3 ...I feel like it can be 32767 (´ ・ ω ・
)
ok = 0
ng = 10**8
while (ok-ng).abs > 1
mi = (ok+ng)/2
begin
Regexp.compile("(.)"*mi)
ok = mi
rescue RegexpError => e
ng = mi
end
end
p ok #=> 32767
** Environmental information **
$ ruby -v
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]
Recommended Posts