Skip to content

Commit

Permalink
Add a explicit exception message when a nil capture group is accessed.
Browse files Browse the repository at this point in the history
  • Loading branch information
karlseguin authored and asterite committed Feb 20, 2017
1 parent 9d04cf3 commit 367e9de
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
8 changes: 7 additions & 1 deletion spec/std/match_data_spec.cr
Expand Up @@ -39,7 +39,13 @@ describe "Regex::MatchData" do

it "raises if outside match range with []" do
"foo" =~ /foo/
expect_raises(IndexError) { $~[1] }
expect_raises(IndexError, "Invalid capture group index: 1") { $~[1] }
end

it "raises if special variable accessed on invalid capture group" do
"spice" =~ /spice(s)?/
expect_raises(IndexError, "Invalid capture group index: 1") { $1 }
expect_raises(IndexError, "Invalid capture group index: 3") { $3 }
end
end

Expand Down
11 changes: 8 additions & 3 deletions src/regex/match_data.cr
Expand Up @@ -129,8 +129,9 @@ class Regex
# ```
def [](n)
check_index_out_of_bounds n

self[n]?.not_nil!
value = self[n]?
raise_invalid_group_index(n) if value.nil?
value
end

# Returns the match of the capture group named by *group_name*, or
Expand Down Expand Up @@ -219,11 +220,15 @@ class Regex
end

private def check_index_out_of_bounds(index)
raise IndexError.new unless valid_group?(index)
raise_invalid_group_index(index) unless valid_group?(index)
end

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

private def raise_invalid_group_index(index)
raise IndexError.new("Invalid capture group index: #{index}")
end
end
end

0 comments on commit 367e9de

Please sign in to comment.