Skip to content

Commit

Permalink
Expose named groups from Pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
jc4x4 authored and sjamesr committed Feb 18, 2021
1 parent b7d3531 commit 2986a5d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions java/com/google/re2j/Pattern.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
package com.google.re2j;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;

/**
* A compiled representation of an RE2 regular expression, mimicking the
Expand Down Expand Up @@ -269,6 +271,14 @@ public int groupCount() {
return re2.numberOfCapturingGroups();
}

/**
* Return a map of the capturing groups in this matcher's pattern, where key is the name and value
* is the index of the group in the pattern.
*/
public Map<String, Integer> namedGroups() {
return Collections.unmodifiableMap(re2.namedGroups);
}

Object readResolve() {
// The deserialized version will be missing the RE2 instance, so we need to create a new,
// compiled version.
Expand Down
25 changes: 25 additions & 0 deletions javatests/com/google/re2j/PatternTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.common.collect.ImmutableMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.util.Collections;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
Expand All @@ -39,6 +42,16 @@ public void testCompile() {
assertEquals(0, p.flags());
}

@Test
public void testCompileExceptionWithDuplicateGroups() {
try {
Pattern.compile("(?P<any>.*)(?P<any>.*");
fail();
} catch (PatternSyntaxException e) {
assertEquals("error parsing regexp: duplicate capture group name: `any`", e.getMessage());
}
}

@Test
public void testToString() {
Pattern p = Pattern.compile("abc");
Expand Down Expand Up @@ -152,6 +165,18 @@ public void testGroupCount() {
ApiTestUtils.testGroupCount("(.*)(\\(a\\)b)(.*)a", 3);
}

@Test
public void testNamedGroups() {
assertNamedGroupsEquals(Collections.<String, Integer>emptyMap(), "hello");
assertNamedGroupsEquals(Collections.<String, Integer>emptyMap(), "(.*)");
assertNamedGroupsEquals(ImmutableMap.of("any", 1), "(?P<any>.*)");
assertNamedGroupsEquals(ImmutableMap.of("foo", 1, "bar", 2), "(?P<foo>.*)(?P<bar>.*)");
}

private static void assertNamedGroupsEquals(Map<String, Integer> expected, String pattern) {
assertEquals(expected, Pattern.compile(pattern).namedGroups());
}

// See https://github.com/google/re2j/issues/93.
@Test
public void testIssue93() {
Expand Down

0 comments on commit 2986a5d

Please sign in to comment.