OSDN Git Service

ruby-1.9.1-rc1
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / test / ruby / test_regexp.rb
1 require 'test/unit'
2
3 class TestRegexp < Test::Unit::TestCase
4   def setup
5     @verbose = $VERBOSE
6     $VERBOSE = nil
7   end
8
9   def teardown
10     $VERBOSE = @verbose
11   end
12
13   def test_ruby_dev_24643
14     assert_nothing_raised("[ruby-dev:24643]") {
15       /(?:(?:[a]*[a])?b)*a*$/ =~ "aabaaca"
16     }
17   end
18
19   def test_ruby_talk_116455
20     assert_match(/^(\w{2,}).* ([A-Za-z\xa2\xc0-\xff]{2,}?)$/n, "Hallo Welt")
21   end
22
23   def test_ruby_dev_24887
24     assert_equal("a".gsub(/a\Z/, ""), "")
25   end
26
27   def test_yoshidam_net_20041111_1
28     s = "[\xC2\xA0-\xC3\xBE]"
29     assert_match(Regexp.new(s, nil, "u"), "\xC3\xBE")
30   end
31
32   def test_yoshidam_net_20041111_2
33     assert_raise(RegexpError) do
34       s = "[\xFF-\xFF]".force_encoding("utf-8")
35       Regexp.new(s, nil, "u")
36     end
37   end
38
39   def test_ruby_dev_31309
40     assert_equal('Ruby', 'Ruby'.sub(/[^a-z]/i, '-'))
41   end
42
43   def test_assert_normal_exit
44     # moved from knownbug.  It caused core.
45     Regexp.union("a", "a")
46   end
47
48   def test_to_s
49     assert_equal '(?-mix:\x00)', Regexp.new("\0").to_s
50   end
51
52   def test_union
53     assert_equal :ok, begin
54       Regexp.union(
55         "a",
56         Regexp.new("\xc2\xa1".force_encoding("euc-jp")),
57         Regexp.new("\xc2\xa1".force_encoding("utf-8")))
58       :ng
59     rescue ArgumentError
60       :ok
61     end
62   end
63
64   def test_named_capture
65     m = /&(?<foo>.*?);/.match("aaa &amp; yyy")
66     assert_equal("amp", m["foo"])
67     assert_equal("amp", m[:foo])
68     assert_equal(5, m.begin(:foo))
69     assert_equal(8, m.end(:foo))
70     assert_equal([5,8], m.offset(:foo))
71
72     assert_equal("aaa [amp] yyy",
73       "aaa &amp; yyy".sub(/&(?<foo>.*?);/, '[\k<foo>]'))
74
75     assert_equal('#<MatchData "&amp; y" foo:"amp">',
76       /&(?<foo>.*?); (y)/.match("aaa &amp; yyy").inspect)
77     assert_equal('#<MatchData "&amp; y" 1:"amp" 2:"y">',
78       /&(.*?); (y)/.match("aaa &amp; yyy").inspect)
79     assert_equal('#<MatchData "&amp; y" foo:"amp" bar:"y">',
80       /&(?<foo>.*?); (?<bar>y)/.match("aaa &amp; yyy").inspect)
81     assert_equal('#<MatchData "&amp; y" foo:"amp" foo:"y">',
82       /&(?<foo>.*?); (?<foo>y)/.match("aaa &amp; yyy").inspect)
83
84     /(?<id>[A-Za-z_]+)/ =~ "!abc"
85     assert_equal("abc", Regexp.last_match(:id))
86
87     /a/ =~ "b" # doesn't match.
88     assert_equal(nil, Regexp.last_match)
89     assert_equal(nil, Regexp.last_match(1))
90     assert_equal(nil, Regexp.last_match(:foo))
91
92     assert_equal(["foo", "bar"], /(?<foo>.)(?<bar>.)/.names)
93     assert_equal(["foo"], /(?<foo>.)(?<foo>.)/.names)
94     assert_equal([], /(.)(.)/.names)
95
96     assert_equal(["foo", "bar"], /(?<foo>.)(?<bar>.)/.match("ab").names)
97     assert_equal(["foo"], /(?<foo>.)(?<foo>.)/.match("ab").names)
98     assert_equal([], /(.)(.)/.match("ab").names)
99
100     assert_equal({"foo"=>[1], "bar"=>[2]},
101                  /(?<foo>.)(?<bar>.)/.named_captures)
102     assert_equal({"foo"=>[1, 2]},
103                  /(?<foo>.)(?<foo>.)/.named_captures)
104     assert_equal({}, /(.)(.)/.named_captures)
105
106     assert_equal("a[b]c", "abc".sub(/(?<x>[bc])/, "[\\k<x>]"))
107   end
108
109   def test_assign_named_capture
110     assert_equal("a", eval('/(?<foo>.)/ =~ "a"; foo'))
111     assert_equal("a", eval('foo = 1; /(?<foo>.)/ =~ "a"; foo'))
112     assert_equal("a", eval('1.times {|foo| /(?<foo>.)/ =~ "a"; break foo }'))
113     assert_nothing_raised { eval('/(?<Foo>.)/ =~ "a"') }
114     assert_nil(eval('/(?<Foo>.)/ =~ "a"; defined? Foo'))
115   end
116
117   def test_assign_named_capture_to_reserved_word
118     /(?<nil>.)/ =~ "a"
119     assert(!local_variables.include?(:nil), "[ruby-dev:32675]")
120   end
121
122   def test_match_regexp
123     r = /./
124     m = r.match("a")
125     assert_equal(r, m.regexp)
126     re = /foo/
127     assert_equal(re, re.match("foo").regexp)
128   end
129
130   def test_source
131     assert_equal('', //.source)
132   end
133
134   def test_inspect
135     assert_equal('//', //.inspect)
136     assert_equal('//i', //i.inspect)
137     assert_equal('/\//i', /\//i.inspect)
138     assert_equal('/\//i', /#{'/'}/i.inspect)
139     assert_equal('/\/x/i', /\/x/i.inspect)
140     assert_equal('/\x00/i', /#{"\0"}/i.inspect)
141     assert_equal("/\n/i", /#{"\n"}/i.inspect)
142     s = [0xff].pack("C")
143     assert_equal('/\/'+s+'/i', /\/#{s}/i.inspect)
144   end
145
146   def test_char_to_option
147     assert_equal("BAR", "FOOBARBAZ"[/b../i])
148     assert_equal("bar", "foobarbaz"[/  b  .  .  /x])
149     assert_equal("bar\n", "foo\nbar\nbaz"[/b.../m])
150     assert_raise(SyntaxError) { eval('//z') }
151   end
152
153   def test_char_to_option_kcode
154     assert_equal("bar", "foobarbaz"[/b../s])
155     assert_equal("bar", "foobarbaz"[/b../e])
156     assert_equal("bar", "foobarbaz"[/b../u])
157   end
158
159   def test_to_s2
160     assert_equal('(?-mix:foo)', /(?:foo)/.to_s)
161     assert_equal('(?m-ix:foo)', /(?:foo)/m.to_s)
162     assert_equal('(?mi-x:foo)', /(?:foo)/mi.to_s)
163     assert_equal('(?mix:foo)', /(?:foo)/mix.to_s)
164     assert_equal('(?m-ix:foo)', /(?m-ix:foo)/.to_s)
165     assert_equal('(?mi-x:foo)', /(?mi-x:foo)/.to_s)
166     assert_equal('(?mix:foo)', /(?mix:foo)/.to_s)
167     assert_equal('(?mix:)', /(?mix)/.to_s)
168     assert_equal('(?-mix:(?mix:foo) )', /(?mix:foo) /.to_s)
169   end
170
171   def test_casefold_p
172     assert_equal(false, /a/.casefold?)
173     assert_equal(true, /a/i.casefold?)
174     assert_equal(false, /(?i:a)/.casefold?)
175   end
176
177   def test_options
178     assert_equal(Regexp::IGNORECASE, /a/i.options)
179     assert_equal(Regexp::EXTENDED, /a/x.options)
180     assert_equal(Regexp::MULTILINE, /a/m.options)
181   end
182
183   def test_match_init_copy
184     m = /foo/.match("foo")
185     assert_equal(/foo/, m.dup.regexp)
186     assert_raise(TypeError) do
187       m.instance_eval { initialize_copy(nil) }
188     end
189     assert_equal([0, 3], m.offset(0))
190     assert_equal(/foo/, m.dup.regexp)
191   end
192
193   def test_match_size
194     m = /(.)(.)(\d+)(\d)/.match("THX1138.")
195     assert_equal(5, m.size)
196   end
197
198   def test_match_offset_begin_end
199     m = /(?<x>b..)/.match("foobarbaz")
200     assert_equal([3, 6], m.offset("x"))
201     assert_equal(3, m.begin("x"))
202     assert_equal(6, m.end("x"))
203     assert_raise(IndexError) { m.offset("y") }
204     assert_raise(IndexError) { m.offset(2) }
205     assert_raise(IndexError) { m.begin(2) }
206     assert_raise(IndexError) { m.end(2) }
207
208     m = /(?<x>q..)?/.match("foobarbaz")
209     assert_equal([nil, nil], m.offset("x"))
210     assert_equal(nil, m.begin("x"))
211     assert_equal(nil, m.end("x"))
212
213     m = /\A\u3042(.)(.)?(.)\z/.match("\u3042\u3043\u3044")
214     assert_equal([1, 2], m.offset(1))
215     assert_equal([nil, nil], m.offset(2))
216     assert_equal([2, 3], m.offset(3))
217   end
218
219   def test_match_to_s
220     m = /(?<x>b..)/.match("foobarbaz")
221     assert_equal("bar", m.to_s)
222   end
223
224   def test_match_pre_post
225     m = /(?<x>b..)/.match("foobarbaz")
226     assert_equal("foo", m.pre_match)
227     assert_equal("baz", m.post_match)
228   end
229
230   def test_match_array
231     m = /(...)(...)(...)(...)?/.match("foobarbaz")
232     assert_equal(["foobarbaz", "foo", "bar", "baz", nil], m.to_a)
233   end
234
235   def test_match_captures
236     m = /(...)(...)(...)(...)?/.match("foobarbaz")
237     assert_equal(["foo", "bar", "baz", nil], m.captures)
238   end
239
240   def test_match_aref
241     m = /(...)(...)(...)(...)?/.match("foobarbaz")
242     assert_equal("foo", m[1])
243     assert_equal(["foo", "bar", "baz"], m[1..3])
244     assert_nil(m[5])
245     assert_raise(IndexError) { m[:foo] }
246   end
247
248   def test_match_values_at
249     m = /(...)(...)(...)(...)?/.match("foobarbaz")
250     assert_equal(["foo", "bar", "baz"], m.values_at(1, 2, 3))
251   end
252
253   def test_match_string
254     m = /(?<x>b..)/.match("foobarbaz")
255     assert_equal("foobarbaz", m.string)
256   end
257
258   def test_match_inspect
259     m = /(...)(...)(...)(...)?/.match("foobarbaz")
260     assert_equal('#<MatchData "foobarbaz" 1:"foo" 2:"bar" 3:"baz" 4:nil>', m.inspect)
261   end
262
263   def test_initialize
264     assert_raise(ArgumentError) { Regexp.new }
265     assert_equal(/foo/, Regexp.new(/foo/, Regexp::IGNORECASE))
266     re = /foo/
267     assert_raise(SecurityError) do
268       Thread.new { $SAFE = 4; re.instance_eval { initialize(re) } }.join
269     end
270     re.taint
271     assert_raise(SecurityError) do
272       Thread.new { $SAFE = 4; re.instance_eval { initialize(re) } }.join
273     end
274
275     assert_equal(Encoding.find("US-ASCII"), Regexp.new("b..", nil, "n").encoding)
276     assert_equal("bar", "foobarbaz"[Regexp.new("b..", nil, "n")])
277     assert_equal(//n, Regexp.new("", nil, "n"))
278
279     assert_raise(RegexpError) { Regexp.new(")(") }
280   end
281
282   def test_unescape
283     assert_raise(ArgumentError) { s = '\\'; /#{ s }/ }
284     assert_equal(/\177/, (s = '\177'; /#{ s }/))
285     assert_raise(ArgumentError) { s = '\u'; /#{ s }/ }
286     assert_raise(ArgumentError) { s = '\u{ ffffffff }'; /#{ s }/ }
287     assert_raise(ArgumentError) { s = '\u{ ffffff }'; /#{ s }/ }
288     assert_raise(ArgumentError) { s = '\u{ ffff X }'; /#{ s }/ }
289     assert_raise(ArgumentError) { s = '\u{ }'; /#{ s }/ }
290     assert_equal("b", "abc"[(s = '\u{0062}'; /#{ s }/)])
291     assert_equal("b", "abc"[(s = '\u0062'; /#{ s }/)])
292     assert_raise(ArgumentError) { s = '\u0'; /#{ s }/ }
293     assert_raise(ArgumentError) { s = '\u000X'; /#{ s }/ }
294     assert_raise(ArgumentError) { s = "\xff" + '\u3042'; /#{ s }/ }
295     assert_raise(ArgumentError) { s = '\u3042' + [0xff].pack("C"); /#{ s }/ }
296     assert_raise(SyntaxError) { s = ''; eval(%q(/\u#{ s }/)) }
297
298     assert_equal(/a/, eval(%q(s="\u0061";/#{s}/n)))
299     assert_raise(RegexpError) { s = "\u3042"; eval(%q(/#{s}/n)) }
300     assert_raise(RegexpError) { s = "\u0061"; eval(%q(/\u3042#{s}/n)) }
301     assert_raise(ArgumentError) { s1=[0xff].pack("C"); s2="\u3042"; eval(%q(/#{s1}#{s2}/)) }
302
303     assert_raise(ArgumentError) { s = '\x'; /#{ s }/ }
304
305     assert_equal("\xe1", [0x00, 0xe1, 0xff].pack("C*")[/\M-a/])
306     assert_equal("\xdc", [0x00, 0xdc, 0xff].pack("C*")[/\M-\\/])
307     assert_equal("\x8a", [0x00, 0x8a, 0xff].pack("C*")[/\M-\n/])
308     assert_equal("\x89", [0x00, 0x89, 0xff].pack("C*")[/\M-\t/])
309     assert_equal("\x8d", [0x00, 0x8d, 0xff].pack("C*")[/\M-\r/])
310     assert_equal("\x8c", [0x00, 0x8c, 0xff].pack("C*")[/\M-\f/])
311     assert_equal("\x8b", [0x00, 0x8b, 0xff].pack("C*")[/\M-\v/])
312     assert_equal("\x87", [0x00, 0x87, 0xff].pack("C*")[/\M-\a/])
313     assert_equal("\x9b", [0x00, 0x9b, 0xff].pack("C*")[/\M-\e/])
314     assert_equal("\x01", [0x00, 0x01, 0xff].pack("C*")[/\C-a/])
315
316     assert_raise(ArgumentError) { s = '\M'; /#{ s }/ }
317     assert_raise(ArgumentError) { s = '\M-\M-a'; /#{ s }/ }
318     assert_raise(ArgumentError) { s = '\M-\\'; /#{ s }/ }
319
320     assert_raise(ArgumentError) { s = '\C'; /#{ s }/ }
321     assert_raise(ArgumentError) { s = '\c'; /#{ s }/ }
322     assert_raise(ArgumentError) { s = '\C-\C-a'; /#{ s }/ }
323
324     assert_raise(ArgumentError) { s = '\M-\z'; /#{ s }/ }
325     assert_raise(ArgumentError) { s = '\M-\777'; /#{ s }/ }
326
327     assert_equal("\u3042\u3042", "\u3042\u3042"[(s = "\u3042" + %q(\xe3\x81\x82); /#{s}/)])
328     assert_raise(ArgumentError) { s = "\u3042" + %q(\xe3); /#{s}/ }
329     assert_raise(ArgumentError) { s = "\u3042" + %q(\xe3\xe3); /#{s}/ }
330     assert_raise(ArgumentError) { s = '\u3042' + [0xff].pack("C"); /#{s}/ }
331
332     assert_raise(SyntaxError) { eval("/\u3042/n") }
333
334     s = ".........."
335     5.times { s.sub!(".", "") }
336     assert_equal(".....", s)
337   end
338
339   def test_equal
340     assert_equal(true, /abc/ == /abc/)
341     assert_equal(false, /abc/ == /abc/m)
342     assert_equal(false, /abc/ == /abd/)
343   end
344
345   def test_match
346     assert_nil(//.match(nil))
347     assert_equal("abc", /.../.match(:abc)[0])
348     assert_raise(TypeError) { /.../.match(Object.new)[0] }
349     assert_equal("bc", /../.match('abc', 1)[0])
350     assert_equal("bc", /../.match('abc', -2)[0])
351     assert_nil(/../.match("abc", -4))
352     assert_nil(/../.match("abc", 4))
353     assert_equal('\x', /../n.match("\u3042" + '\x', 1)[0])
354
355     r = nil
356     /.../.match("abc") {|m| r = m[0] }
357     assert_equal("abc", r)
358
359     $_ = "abc"; assert_equal(1, ~/bc/)
360     $_ = "abc"; assert_nil(~/d/)
361     $_ = nil; assert_nil(~/./)
362   end
363
364   def test_eqq
365     assert_equal(false, /../ === nil)
366   end
367
368   def test_quote
369     assert_equal("\xff", Regexp.quote([0xff].pack("C")))
370     assert_equal("\\ ", Regexp.quote("\ "))
371     assert_equal("\\t", Regexp.quote("\t"))
372     assert_equal("\\n", Regexp.quote("\n"))
373     assert_equal("\\r", Regexp.quote("\r"))
374     assert_equal("\\f", Regexp.quote("\f"))
375     assert_equal("\\v", Regexp.quote("\v"))
376     assert_equal("\u3042\\t", Regexp.quote("\u3042\t"))
377     assert_equal("\\t\xff", Regexp.quote("\t" + [0xff].pack("C")))
378   end
379
380   def test_try_convert
381     assert_equal(/re/, Regexp.try_convert(/re/))
382     assert_nil(Regexp.try_convert("re"))
383
384     o = Object.new
385     assert_nil(Regexp.try_convert(o))
386     def o.to_regexp() /foo/ end
387     assert_equal(/foo/, Regexp.try_convert(o))
388   end
389
390   def test_union2
391     assert_equal(/(?!)/, Regexp.union)
392     assert_equal(/foo/, Regexp.union(/foo/))
393     assert_equal(/foo/, Regexp.union([/foo/]))
394     assert_equal(/\t/, Regexp.union("\t"))
395     assert_equal(/(?-mix:\u3042)|(?-mix:\u3042)/, Regexp.union(/\u3042/, /\u3042/))
396     assert_equal("\u3041", "\u3041"[Regexp.union(/\u3042/, "\u3041")])
397   end
398
399   def test_dup
400     assert_equal(//, //.dup)
401     assert_raise(TypeError) { //.instance_eval { initialize_copy(nil) } }
402   end
403
404   def test_regsub
405     assert_equal("fooXXXbaz", "foobarbaz".sub!(/bar/, "XXX"))
406     s = [0xff].pack("C")
407     assert_equal(s, "X".sub!(/./, s))
408     assert_equal('\\' + s, "X".sub!(/./, '\\' + s))
409     assert_equal('\k', "foo".sub!(/.../, '\k'))
410     assert_raise(RuntimeError) { "foo".sub!(/(?<x>o)/, '\k<x') }
411     assert_equal('foo[bar]baz', "foobarbaz".sub!(/(b..)/, '[\0]'))
412     assert_equal('foo[foo]baz', "foobarbaz".sub!(/(b..)/, '[\`]'))
413     assert_equal('foo[baz]baz', "foobarbaz".sub!(/(b..)/, '[\\\']'))
414     assert_equal('foo[r]baz', "foobarbaz".sub!(/(b)(.)(.)/, '[\+]'))
415     assert_equal('foo[\\]baz', "foobarbaz".sub!(/(b..)/, '[\\\\]'))
416     assert_equal('foo[\z]baz', "foobarbaz".sub!(/(b..)/, '[\z]'))
417   end
418
419   def test_KCODE
420     assert_nil($KCODE)
421     assert_nothing_raised { $KCODE = nil }
422     assert_equal(false, $=)
423     assert_nothing_raised { $= = nil }
424   end
425
426   def test_match_setter
427     /foo/ =~ "foo"
428     m = $~
429     /bar/ =~ "bar"
430     $~ = m
431     assert_equal("foo", $&)
432   end
433
434   def test_last_match
435     /(...)(...)(...)(...)?/.match("foobarbaz")
436     assert_equal("foobarbaz", Regexp.last_match(0))
437     assert_equal("foo", Regexp.last_match(1))
438     assert_nil(Regexp.last_match(5))
439     assert_nil(Regexp.last_match(-1))
440   end
441
442   def test_getter
443     alias $__REGEXP_TEST_LASTMATCH__ $&
444     alias $__REGEXP_TEST_PREMATCH__ $`
445     alias $__REGEXP_TEST_POSTMATCH__ $'
446     alias $__REGEXP_TEST_LASTPARENMATCH__ $+
447     /(b)(.)(.)/.match("foobarbaz")
448     assert_equal("bar", $__REGEXP_TEST_LASTMATCH__)
449     assert_equal("foo", $__REGEXP_TEST_PREMATCH__)
450     assert_equal("baz", $__REGEXP_TEST_POSTMATCH__)
451     assert_equal("r", $__REGEXP_TEST_LASTPARENMATCH__)
452
453     /(...)(...)(...)/.match("foobarbaz")
454     assert_equal("baz", $+)
455   end
456
457   def test_rindex_regexp
458     assert_equal(3, "foobarbaz\u3042".rindex(/b../n, 5))
459   end
460
461   def test_taint
462     m = Thread.new do
463       "foo"[/foo/]
464       $SAFE = 4
465       /foo/.match("foo")
466     end.value
467     assert(m.tainted?)
468   end
469
470   def check(re, ss, fs = [])
471     re = Regexp.new(re) unless re.is_a?(Regexp)
472     ss = [ss] unless ss.is_a?(Array)
473     ss.each do |e, s|
474       s ||= e
475       assert_match(re, s)
476       m = re.match(s)
477       assert_equal(e, m[0])
478     end
479     fs = [fs] unless fs.is_a?(Array)
480     fs.each {|s| assert_no_match(re, s) }
481   end
482
483   def failcheck(re)
484     assert_raise(RegexpError) { /#{ re }/ }
485   end
486
487   def test_parse
488     check(/\*\+\?\{\}\|\(\)\<\>\`\'/, "*+?{}|()<>`'")
489     check(/\A\w\W\z/, %w(a. b!), %w(.. ab))
490     check(/\A.\b.\b.\B.\B.\z/, %w(a.aaa .a...), %w(aaaaa .....))
491     check(/\A\s\S\z/, [' a', "\n."], ['  ', "\n\n", 'a '])
492     check(/\A\d\D\z/, '0a', %w(00 aa))
493     check(/\A\h\H\z/, %w(0g ag BH), %w(a0 af GG))
494     check(/\Afoo\Z\s\z/, "foo\n", ["foo", "foo\nbar"])
495     assert_equal(%w(a b c), "abc def".scan(/\G\w/))
496     check(/\A\u3042\z/, "\u3042", ["", "\u3043", "a"])
497     check(/\A(..)\1\z/, %w(abab ....), %w(abba aba))
498     failcheck('\1')
499     check(/\A\80\z/, "80", ["\100", ""])
500     check(/\A\77\z/, "?")
501     check(/\A\78\z/, "\7" + '8', ["\100", ""])
502     check(/\A\Qfoo\E\z/, "QfooE")
503     check(/\Aa++\z/, "aaa")
504     check('\Ax]\z', "x]")
505     check(/x#foo/x, "x", "#foo")
506     check(/\Ax#foo#{ "\n" }x\z/x, "xx", ["x", "x#foo\nx"])
507     check(/\A\p{Alpha}\z/, ["a", "z"], [".", "", ".."])
508     check(/\A\p{^Alpha}\z/, [".", "!"], ["!a", ""])
509     check(/\A\n\z/, "\n")
510     check(/\A\t\z/, "\t")
511     check(/\A\r\z/, "\r")
512     check(/\A\f\z/, "\f")
513     check(/\A\a\z/, "\007")
514     check(/\A\e\z/, "\033")
515     check(/\A\v\z/, "\v")
516     failcheck('(')
517     failcheck('(?foo)')
518     failcheck('/\p{foobarbazqux}/')
519     failcheck('/\p{foobarbazqux' + 'a' * 1000 + '}/')
520     failcheck('/[1-\w]/')
521   end
522
523   def test_exec
524     check(/A*B/, %w(B AB AAB AAAB), %w(A))
525     check(/\w*!/, %w(! a! ab! abc!), %w(abc))
526     check(/\w*\W/, %w(! a" ab# abc$), %w(abc))
527     check(/\w*\w/, %w(z az abz abcz), %w(!))
528     check(/[a-z]*\w/, %w(z az abz abcz), %w(!))
529     check(/[a-z]*\W/, %w(! a" ab# abc$), %w(A))
530     check(/((a|bb|ccc|dddd)(1|22|333|4444))/i, %w(a1 bb1 a22), %w(a2 b1))
531     check(/\u0080/, (1..4).map {|i| ["\u0080", "\u0080" * i] }, ["\u0081"])
532     check(/\u0080\u0080/, (2..4).map {|i| ["\u0080" * 2, "\u0080" * i] }, ["\u0081"])
533     check(/\u0080\u0080\u0080/, (3..4).map {|i| ["\u0080" * 3, "\u0080" * i] }, ["\u0081"])
534     check(/\u0080\u0080\u0080\u0080/, (4..4).map {|i| ["\u0080" * 4, "\u0080" * i] }, ["\u0081"])
535     check(/[^\u3042\u3043\u3044]/, %W(a b \u0080 \u3041 \u3045), %W(\u3042 \u3043 \u3044))
536     check(/a.+/m, %W(a\u0080 a\u0080\u0080 a\u0080\u0080\u0080), %W(a))
537     check(/a.+z/m, %W(a\u0080z a\u0080\u0080z a\u0080\u0080\u0080z), %W(az))
538     check(/abc\B.\Bxyz/, %w(abcXxyz abc0xyz), %w(abc|xyz abc-xyz))
539     check(/\Bxyz/, [%w(xyz abcXxyz), %w(xyz abc0xyz)], %w(abc xyz abc-xyz))
540     check(/abc\B/, [%w(abc abcXxyz), %w(abc abc0xyz)], %w(abc xyz abc-xyz))
541     failcheck('(?<foo>abc)\1')
542     check(/^(A+|B+)(?>\g<1>)*[BC]$/, %w(AC BC ABC BAC AABBC), %w(AABB))
543     check(/^(A+|B(?>\g<1>)*)[AC]$/, %w(AAAC BBBAAAAC), %w(BBBAAA))
544     check(/^()(?>\g<1>)*$/, "", "a")
545     check(/^(?>(?=a)(#{ "a" * 1000 }|))++$/, ["a" * 1000, "a" * 2000, "a" * 3000], ["", "a" * 500, "b" * 1000])
546     check(eval('/^(?:a?)?$/'), ["", "a"], ["aa"])
547     check(eval('/^(?:a+)?$/'), ["", "a", "aa"], ["ab"])
548     check(/^(?:a?)+?$/, ["", "a", "aa"], ["ab"])
549     check(/^a??[ab]/, [["a", "a"], ["a", "aa"], ["b", "b"], ["a", "ab"]], ["c"])
550     check(/^(?:a*){3,5}$/, ["", "a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"], ["b"])
551     check(/^(?:a+){3,5}$/, ["aaa", "aaaa", "aaaaa", "aaaaaa"], ["", "a", "aa", "b"])
552   end
553
554   def test_parse_look_behind
555     check(/(?<=A)B(?=C)/, [%w(B ABC)], %w(aBC ABc aBc))
556     check(/(?<!A)B(?!C)/, [%w(B aBc)], %w(ABC aBC ABc))
557     failcheck('(?<=.*)')
558     failcheck('(?<!.*)')
559     check(/(?<=A|B.)C/, [%w(C AC), %w(C BXC)], %w(C BC))
560     check(/(?<!A|B.)C/, [%w(C C), %w(C BC)], %w(AC BXC))
561   end
562
563   def test_parse_kg
564     check(/\A(.)(.)\k<1>(.)\z/, %w(abac abab ....), %w(abcd aaba xxx))
565     check(/\A(.)(.)\k<-1>(.)\z/, %w(abbc abba ....), %w(abcd aaba xxx))
566     check(/\A(?<n>.)(?<x>\g<n>){0}(?<y>\k<n+0>){0}\g<x>\g<y>\z/, "aba", "abb")
567     check(/\A(?<n>.)(?<x>\g<n>){0}(?<y>\k<n+1>){0}\g<x>\g<y>\z/, "abb", "aba")
568     check(/\A(?<x>..)\k<x>\z/, %w(abab ....), %w(abac abba xxx))
569     check(/\A(.)(..)\g<-1>\z/, "abcde", %w(.... ......))
570     failcheck('\k<x>')
571     failcheck('\k<')
572     failcheck('\k<>')
573     failcheck('\k<.>')
574     failcheck('\k<x.>')
575     failcheck('\k<1.>')
576     failcheck('\k<x')
577     failcheck('\k<x+')
578     failcheck('()\k<-2>')
579     failcheck('()\g<-2>')
580     check(/\A(?<x>.)(?<x>.)\k<x>\z/, %w(aba abb), %w(abc .. ....))
581     check(/\A(?<x>.)(?<x>.)\k<x>\z/i, %w(aba ABa abb ABb), %w(abc .. ....))
582     check(/\k\g/, "kg")
583     failcheck('(.\g<1>)')
584     failcheck('(.\g<2>)')
585     failcheck('(?=\g<1>)')
586     failcheck('((?=\g<1>))')
587     failcheck('(\g<1>|.)')
588     failcheck('(.|\g<1>)')
589     check(/(!)(?<=(a)|\g<1>)/, ["!"], %w(a))
590     check(/^(a|b\g<1>c)$/, %w(a bac bbacc bbbaccc), %w(bbac bacc))
591     check(/^(a|b\g<2>c)(B\g<1>C){0}$/, %w(a bBaCc bBbBaCcCc bBbBbBaCcCcCc), %w(bBbBaCcC BbBaCcCc))
592     check(/\A(?<n>.|X\g<n>)(?<x>\g<n>){0}(?<y>\k<n+0>){0}\g<x>\g<y>\z/, "XXaXbXXa", %w(XXabXa abb))
593     check(/\A(?<n>.|X\g<n>)(?<x>\g<n>){0}(?<y>\k<n+1>){0}\g<x>\g<y>\z/, "XaXXbXXb", %w(aXXbXb aba))
594     failcheck('(?<x>)(?<x>)(\g<x>)')
595     check(/^(?<x>foo)(bar)\k<x>/, %w(foobarfoo), %w(foobar barfoo))
596     check(/^(?<a>f)(?<a>o)(?<a>o)(?<a>b)(?<a>a)(?<a>r)(?<a>b)(?<a>a)(?<a>z)\k<a>{9}$/, %w(foobarbazfoobarbaz foobarbazbazbarfoo foobarbazzabraboof), %w(foobar barfoo))
597   end
598
599   def test_parse_curly_brace
600     check(/\A{/, ["{", ["{", "{x"]])
601     check(/\A{ /, ["{ ", ["{ ", "{ x"]])
602     check(/\A{,}\z/, "{,}")
603     check(/\A{}\z/, "{}")
604     check(/\Aa{0}+\z/, "", %w(a aa aab))
605     check(/\Aa{1}+\z/, %w(a aa), ["", "aab"])
606     check(/\Aa{1,2}b{1,2}\z/, %w(ab aab abb aabb), ["", "aaabb", "abbb"])
607     check(/(?!x){0,1}/, [ ['', 'ab'], ['', ''] ])
608     check(/c\z{0,1}/, [ ['c', 'abc'], ['c', 'cab']], ['abd'])
609     check(/\A{0,1}a/, [ ['a', 'abc'], ['a', '____abc']], ['bcd'])
610     failcheck('.{100001}')
611     failcheck('.{0,100001}')
612     failcheck('.{1,0}')
613     failcheck('{0}')
614   end
615
616   def test_parse_comment
617     check(/\A(?#foo\)bar)\z/, "", "a")
618     failcheck('(?#')
619   end
620
621   def test_char_type
622     check(/\u3042\d/, ["\u30421", "\u30422"])
623
624     # CClassTable cache test
625     assert(/\u3042\d/.match("\u30421"))
626     assert(/\u3042\d/.match("\u30422"))
627   end
628
629   def test_char_class
630     failcheck('[]')
631     failcheck('[x')
632     check('\A[]]\z', "]", "")
633     check('\A[]\.]+\z', %w(] . ]..]), ["", "["])
634     check(/\A[\u3042]\z/, "\u3042", "\u3042aa")
635     check(/\A[\u3042\x61]+\z/, ["aa\u3042aa", "\u3042\u3042", "a"], ["", "b"])
636     check(/\A[\u3042\x61\x62]+\z/, "abab\u3042abab\u3042")
637     check(/\A[abc]+\z/, "abcba", ["", "ada"])
638     check(/\A[\w][\W]\z/, %w(a. b!), %w(.. ab))
639     check(/\A[\s][\S]\z/, [' a', "\n."], ['  ', "\n\n", 'a '])
640     check(/\A[\d][\D]\z/, '0a', %w(00 aa))
641     check(/\A[\h][\H]\z/, %w(0g ag BH), %w(a0 af GG))
642     check(/\A[\p{Alpha}]\z/, ["a", "z"], [".", "", ".."])
643     check(/\A[\p{^Alpha}]\z/, [".", "!"], ["!a", ""])
644     check(/\A[\xff]\z/, "\xff", ["", "\xfe"])
645     check(/\A[\80]+\z/, "8008", ["\\80", "\100", "\1000"])
646     check(/\A[\77]+\z/, "???")
647     check(/\A[\78]+\z/, "\788\7")
648     check(/\A[\0]\z/, "\0")
649     check(/\A[[:0]]\z/, [":", "0"], ["", ":0"])
650     check(/\A[0-]\z/, ["0", "-"], "0-")
651     check('\A[a-&&\w]\z', "a", "-")
652     check('\A[--0]\z', ["-", "/", "0"], ["", "1"])
653     check('\A[\'--0]\z', %w(* + \( \) 0 ,), ["", ".", "1"])
654     check(/\A[a-b-]\z/, %w(a b -), ["", "c"])
655     check('\A[a-b-&&\w]\z', %w(a b), ["", "-"])
656     check('\A[a-b-&&\W]\z', "-", ["", "a", "b"])
657     check('\A[a-c-e]\z', %w(a b c e), %w(- d)) # is it OK?
658     check(/\A[a-f&&[^b-c]&&[^e]]\z/, %w(a d f), %w(b c e g 0))
659     check(/\A[[^b-c]&&[^e]&&a-f]\z/, %w(a d f), %w(b c e g 0))
660     check(/\A[\n\r\t]\z/, ["\n", "\r", "\t"])
661     failcheck('[9-1]')
662   end
663
664   def test_posix_bracket
665     check(/\A[[:alpha:]0]\z/, %w(0 a), %w(1 .))
666     check(/\A[[:^alpha:]0]\z/, %w(0 1 .), "a")
667     check(/\A[[:alpha\:]]\z/, %w(a l p h a :), %w(b 0 1 .))
668     check(/\A[[:alpha:foo]0]\z/, %w(0 a), %w(1 .))
669     check(/\A[[:xdigit:]&&[:alpha:]]\z/, "a", %w(g 0))
670     check('\A[[:abcdefghijklmnopqrstu:]]+\z', "[]")
671     failcheck('[[:alpha')
672     failcheck('[[:alpha:')
673     failcheck('[[:alp:]]')
674   end
675
676   def test_backward
677     assert_equal(3, "foobar".rindex(/b.r/i))
678     assert_equal(nil, "foovar".rindex(/b.r/i))
679     assert_equal(3, ("foo" + "bar" * 1000).rindex(/#{"bar"*1000}/))
680     assert_equal(4, ("foo\nbar\nbaz\n").rindex(/bar/i))
681   end
682
683   def test_uninitialized
684     assert_raise(TypeError) { Regexp.allocate.hash }
685     assert_raise(TypeError) { Regexp.allocate.eql? Regexp.allocate }
686     assert_raise(TypeError) { Regexp.allocate == Regexp.allocate }
687     assert_raise(TypeError) { Regexp.allocate =~ "" }
688     assert_equal(false, Regexp.allocate === Regexp.allocate)
689     assert_nil(~Regexp.allocate)
690     assert_raise(TypeError) { Regexp.allocate.match("") }
691     assert_raise(TypeError) { Regexp.allocate.to_s }
692     assert_match(/^#<Regexp:.*>$/, Regexp.allocate.inspect)
693     assert_raise(TypeError) { Regexp.allocate.source }
694     assert_raise(TypeError) { Regexp.allocate.casefold? }
695     assert_raise(TypeError) { Regexp.allocate.options }
696     assert_equal(Encoding.find("ASCII-8BIT"), Regexp.allocate.encoding)
697     assert_equal(false, Regexp.allocate.fixed_encoding?)
698     assert_raise(TypeError) { Regexp.allocate.names }
699     assert_raise(TypeError) { Regexp.allocate.named_captures }
700
701     assert_raise(TypeError) { MatchData.allocate.regexp }
702     assert_raise(TypeError) { MatchData.allocate.names }
703     assert_raise(TypeError) { MatchData.allocate.size }
704     assert_raise(TypeError) { MatchData.allocate.length }
705     assert_raise(TypeError) { MatchData.allocate.offset(0) }
706     assert_raise(TypeError) { MatchData.allocate.begin(0) }
707     assert_raise(TypeError) { MatchData.allocate.end(0) }
708     assert_raise(TypeError) { MatchData.allocate.to_a }
709     assert_raise(TypeError) { MatchData.allocate[:foo] }
710     assert_raise(TypeError) { MatchData.allocate.captures }
711     assert_raise(TypeError) { MatchData.allocate.values_at }
712     assert_raise(TypeError) { MatchData.allocate.pre_match }
713     assert_raise(TypeError) { MatchData.allocate.post_match }
714     assert_raise(TypeError) { MatchData.allocate.to_s }
715     assert_match(/^#<MatchData:.*>$/, MatchData.allocate.inspect)
716     assert_raise(TypeError) { MatchData.allocate.string }
717     $~ = MatchData.allocate
718     assert_raise(TypeError) { $& }
719     assert_raise(TypeError) { $` }
720     assert_raise(TypeError) { $' }
721     assert_raise(TypeError) { $+ }
722   end
723
724   def test_unicode
725     assert_match(/^\u3042{0}\p{Any}$/, "a")
726     assert_match(/^\u3042{0}\p{Any}$/, "\u3041")
727     assert_match(/^\u3042{0}\p{Any}$/, "\0")
728     assert_no_match(/^\u3042{0}\p{Any}$/, "\0\0")
729     assert_no_match(/^\u3042{0}\p{Any}$/, "")
730     assert_raise(SyntaxError) { eval('/^\u3042{0}\p{' + "\u3042" + '}$/') }
731     assert_raise(SyntaxError) { eval('/^\u3042{0}\p{' + 'a' * 1000 + '}$/') }
732     assert_raise(SyntaxError) { eval('/^\u3042{0}\p{foobarbazqux}$/') }
733     assert_match(/^(\uff21)(a)\1\2$/i, "\uff21A\uff41a")
734     assert_no_match(/^(\uff21)\1$/i, "\uff21A")
735     assert_no_match(/^(\uff41)\1$/i, "\uff41a")
736     assert_match(/^\u00df$/i, "\u00df")
737     assert_match(/^\u00df$/i, "ss")
738     #assert_match(/^(\u00df)\1$/i, "\u00dfss") # this must be bug...
739     assert_match(/^\u00df{2}$/i, "\u00dfss")
740     assert_match(/^\u00c5$/i, "\u00c5")
741     assert_match(/^\u00c5$/i, "\u00e5")
742     assert_match(/^\u00c5$/i, "\u212b")
743     assert_match(/^(\u00c5)\1\1$/i, "\u00c5\u00e5\u212b")
744     assert_match(/^\u0149$/i, "\u0149")
745     assert_match(/^\u0149$/i, "\u02bcn")
746     #assert_match(/^(\u0149)\1$/i, "\u0149\u02bcn") # this must be bug...
747     assert_match(/^\u0149{2}$/i, "\u0149\u02bcn")
748     assert_match(/^\u0390$/i, "\u0390")
749     assert_match(/^\u0390$/i, "\u03b9\u0308\u0301")
750     #assert_match(/^(\u0390)\1$/i, "\u0390\u03b9\u0308\u0301") # this must be bug...
751     assert_match(/^\u0390{2}$/i, "\u0390\u03b9\u0308\u0301")
752     assert_match(/^\ufb05$/i, "\ufb05")
753     assert_match(/^\ufb05$/i, "\ufb06")
754     assert_match(/^\ufb05$/i, "st")
755     #assert_match(/^(\ufb05)\1\1$/i, "\ufb05\ufb06st") # this must be bug...
756     assert_match(/^\ufb05{3}$/i, "\ufb05\ufb06st")
757     assert_match(/^\u03b9\u0308\u0301$/i, "\u0390")
758     assert_nothing_raised { 0x03ffffff.chr("utf-8").size }
759     assert_nothing_raised { 0x7fffffff.chr("utf-8").size }
760   end
761 end