PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/test/ruby/test_regexp.rb

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