summaryrefslogtreecommitdiff
path: root/spec/ruby/library/stringscanner/named_captures_spec.rb
blob: a68d66c216a82eeb5b57bbf9730a4af6ef8a820d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require_relative '../../spec_helper'
require 'strscan'

describe "StringScanner#named_captures" do
  before do
    @s = StringScanner.new('Fri Dec 12 1975 14:39')
  end

  it "returns a hash of names and matched substrings for named capturing groups in a regular expression of the most recent matching" do
    @s.exist?(/(?<wday>\w+) (?<month>\w+) (?<day>\d+)/)
    @s.named_captures.should == {"wday" => "Fri", "month" => "Dec", "day" => "12"}
  end

  it "returns {} if there are no named capturing groups" do
    @s.exist?(/(\w+) (\w+) (\d+)/)
    @s.named_captures.should == {}
  end

  # https://github.com/ruby/strscan/issues/132
  ruby_bug "", ""..."3.3" do # fixed in strscan v3.0.7
    it "returns {} if there is no any matching done" do
      @s.named_captures.should == {}
    end
  end

  it "returns nil for an optional named capturing group if it doesn't match" do
    @s.exist?(/(?<wday>\w+) (?<month>\w+) (?<day>\s+)?/)
    @s.named_captures.should == {"wday" => "Fri", "month" => "Dec", "day" => nil}
  end
end