Skip to content

Commit

Permalink
Added new flag Pattern.LONGEST_MATCH to allow changing hard-coded "lo…
Browse files Browse the repository at this point in the history
…ngest=false" in Pattern.compile()
  • Loading branch information
mykeul committed Dec 5, 2019
1 parent 2953c0d commit 1c00a62
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
13 changes: 10 additions & 3 deletions java/com/google/re2j/Pattern.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public final class Pattern implements Serializable {
*/
public static final int DISABLE_UNICODE_GROUPS = 8;

/**
* Flag: matches longest possible string.
*/
public static final int LONGEST_MATCH = 16;

// The pattern string at construction time.
private final String pattern;

Expand Down Expand Up @@ -117,10 +122,11 @@ public static Pattern compile(String regex, int flags) {
if ((flags & MULTILINE) != 0) {
flregex = "(?m)" + flregex;
}
if ((flags & ~(MULTILINE | DOTALL | CASE_INSENSITIVE | DISABLE_UNICODE_GROUPS)) != 0) {
if ((flags & ~(MULTILINE | DOTALL | CASE_INSENSITIVE | DISABLE_UNICODE_GROUPS | LONGEST_MATCH))
!= 0) {
throw new IllegalArgumentException(
"Flags should only be a combination "
+ "of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS");
+ "of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH");
}
return compile(flregex, regex, flags);
}
Expand All @@ -133,7 +139,8 @@ private static Pattern compile(String flregex, String regex, int flags) {
if ((flags & DISABLE_UNICODE_GROUPS) != 0) {
re2Flags &= ~RE2.UNICODE_GROUPS;
}
return new Pattern(regex, flags, RE2.compileImpl(flregex, re2Flags, /*longest=*/ false));
return new Pattern(
regex, flags, RE2.compileImpl(flregex, re2Flags, (flags & LONGEST_MATCH) != 0));
}

/**
Expand Down
16 changes: 16 additions & 0 deletions javatests/com/google/re2j/MatcherTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -468,4 +468,20 @@ private String appendReplacement(Matcher m, String replacement) {
m.appendReplacement(b, replacement);
return b.toString();
}

@Test
public void testPatternLongestMatch() {
final String pattern = "(?:a+)|(?:a+ b+)";
final String text = "xxx aaa bbb yyy";
{
final Matcher matcher = Pattern.compile(pattern).matcher(text);
assertEquals(true, matcher.find());
assertEquals("aaa", text.substring(matcher.start(), matcher.end()));
}
{
final Matcher matcher = Pattern.compile(pattern, Pattern.LONGEST_MATCH).matcher(text);
assertEquals(true, matcher.find());
assertEquals("aaa bbb", text.substring(matcher.start(), matcher.end()));
}
}
}

0 comments on commit 1c00a62

Please sign in to comment.