nth with not-found on regex matcher returns not-found on last group index

Description

From https://ask.clojure.org/index.php/9740/off-one-error-nth-java-util-regex-matcher-instance-index-found

Given a regex Matcher (from re-matcher), `nth` can be used to look up the nth group in the matches (and the whole match is in 0th index). Can get all matches with re-find / re-groups:

However the not found variant has an index check that fails due to off-by-1 on the last index:

Cause: The code in RT.nthFrom() (not-found arity) checks that the index is < Matcher.groupCount(), but that does not take into the whole string match in index 0.

Proposed: Change check to be <= instead. One special case is when there is NO match and we expect to return the not-found value. In that case groupCount() returns 0, so (nth matcher 0 :not-found) would pass the <= check and invoke matcher.group(0), which will throw. Due to this, we change the condition from:

to:

which guards against the no-match case (where groups = 0).

Patch: clj-2585.patch - fixes bounds check, adds some tests. existing tests in test/clojure/test_clojure/sequences.clj catch the special no-match case above.

Screened: Christian Romney

Environment

None

Activity

Show:
Alex Miller
December 11, 2020, 7:09 PM

Applied for 1.10.2-rc1

Fixed
Your pinned fields
Click on the next to a field label to start pinning.

Assignee

Unassigned

Reporter

Alex Miller

Labels

Approval

Ok

Patch

Code and Test

Priority

Minor

Affects versions

Fix versions