Skip to content

Commit 367e9de

Browse files
karlseguinAry Borenszweig
authored and
Ary Borenszweig
committedFeb 20, 2017
Add a explicit exception message when a nil capture group is accessed.
#3978
1 parent 9d04cf3 commit 367e9de

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed
 

‎spec/std/match_data_spec.cr

+7-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,13 @@ describe "Regex::MatchData" do
3939

4040
it "raises if outside match range with []" do
4141
"foo" =~ /foo/
42-
expect_raises(IndexError) { $~[1] }
42+
expect_raises(IndexError, "Invalid capture group index: 1") { $~[1] }
43+
end
44+
45+
it "raises if special variable accessed on invalid capture group" do
46+
"spice" =~ /spice(s)?/
47+
expect_raises(IndexError, "Invalid capture group index: 1") { $1 }
48+
expect_raises(IndexError, "Invalid capture group index: 3") { $3 }
4349
end
4450
end
4551

‎src/regex/match_data.cr

+8-3
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,9 @@ class Regex
129129
# ```
130130
def [](n)
131131
check_index_out_of_bounds n
132-
133-
self[n]?.not_nil!
132+
value = self[n]?
133+
raise_invalid_group_index(n) if value.nil?
134+
value
134135
end
135136

136137
# Returns the match of the capture group named by *group_name*, or
@@ -219,11 +220,15 @@ class Regex
219220
end
220221

221222
private def check_index_out_of_bounds(index)
222-
raise IndexError.new unless valid_group?(index)
223+
raise_invalid_group_index(index) unless valid_group?(index)
223224
end
224225

225226
private def valid_group?(index)
226227
index <= @size
227228
end
229+
230+
private def raise_invalid_group_index(index)
231+
raise IndexError.new("Invalid capture group index: #{index}")
232+
end
228233
end
229234
end

0 commit comments

Comments
 (0)
Please sign in to comment.