Skip to content

Commit

Permalink
MatchData: support negative index
Browse files Browse the repository at this point in the history
  • Loading branch information
makenowjust authored and asterite committed Jun 20, 2017
1 parent 46e9d81 commit 2f5f9bf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
16 changes: 16 additions & 0 deletions spec/std/match_data_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ describe "Regex::MatchData" do
$~["g2"].should eq("ba")
end

it "can use negative index" do
"foo" =~ /(f)(oo)/
$~[-1].should eq("oo")
$~[-2].should eq("f")
$~[-3].should eq("foo")
expect_raises(IndexError, "Invalid capture group index: -4") { $~[-4] }
end

it "raises exception when named group doesn't exist" do
("foo" =~ /foo/).should eq(0)
expect_raises(KeyError, "Capture group 'group' does not exist") { $~["group"] }
Expand Down Expand Up @@ -85,6 +93,14 @@ describe "Regex::MatchData" do
$~["g2"]?.should eq("ba")
end

it "can use negative index" do
"foo" =~ /(b)?(f)(oo)/
$~[-1]?.should eq("oo")
$~[-2]?.should eq("f")
$~[-3]?.should be_nil
$~[-4]?.should eq("foo")
end

it "returns nil exception when named group doesn't exist" do
("foo" =~ /foo/).should eq(0)
$~["group"]?.should be_nil
Expand Down
7 changes: 6 additions & 1 deletion src/regex/match_data.cr
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ class Regex
# ```
def byte_begin(n = 0)
check_index_out_of_bounds n
n += size if n < 0
@ovector[n * 2]
end

Expand All @@ -109,6 +110,7 @@ class Regex
# ```
def byte_end(n = 0)
check_index_out_of_bounds n
n += size if n < 0
@ovector[n * 2 + 1]
end

Expand All @@ -125,6 +127,7 @@ class Regex
def []?(n)
return unless valid_group?(n)

n += size if n < 0
start = @ovector[n * 2]
finish = @ovector[n * 2 + 1]
return if start < 0
Expand All @@ -140,6 +143,8 @@ class Regex
# ```
def [](n)
check_index_out_of_bounds n
n += size if n < 0

value = self[n]?
raise_capture_group_was_not_matched n if value.nil?
value
Expand Down Expand Up @@ -345,7 +350,7 @@ class Regex
end

private def valid_group?(index)
index < size
-size <= index < size
end

private def raise_invalid_group_index(index)
Expand Down

0 comments on commit 2f5f9bf

Please sign in to comment.