Skip to content

Commit

Permalink
fix: let Matcher#namedGroups() be called multiple times (#27)
Browse files Browse the repository at this point in the history
related #17
fix #26
  • Loading branch information
tony19 authored Oct 15, 2022
1 parent 9674eb8 commit 7506b68
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/main/java/com/google/code/regexp/Matcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,9 @@ public List<Map<String, String>> namedGroups() {
}

int nextIndex = 0;
while (!matcher.hitEnd() && matcher.find(nextIndex)) {
int lastNextIndex = 0;
matcher.reset();
while (matcher.find(nextIndex)) {
Map<String, String> matches = new LinkedHashMap<String, String>();

for (String groupName : groupNames) {
Expand All @@ -329,6 +331,11 @@ public List<Map<String, String>> namedGroups() {
nextIndex = matcher.end();
}

if (nextIndex == lastNextIndex) {
break;
}
lastNextIndex = nextIndex;

result.add(matches);
}
return result;
Expand Down
13 changes: 13 additions & 0 deletions src/test/java/com/google/code/regexp/MatcherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -763,4 +763,17 @@ public void testNamedGroupsReturnsWhenMatchesEmptyString() {
assertEquals(1, groups.size());
assertEquals("bar", groups.get(0).get("foo"));
}

// Issue #26
@Test
public void testNamedGroupsCanBeCalledMultipleTimes() {
final String regex = "/teamDrawer/(?<roomId>.*)";
final String url = "/teamDrawer/12345";

final Matcher matcher = Pattern.compile(regex).matcher(url);
final Integer count = matcher.namedGroups().size();
final Integer mapCount = matcher.namedGroups().get(0).size();
final String value = matcher.namedGroups().get(0).get("roomId");
assertEquals("12345", value);
}
}

0 comments on commit 7506b68

Please sign in to comment.