diff --git a/java/com/google/re2j/Pattern.java b/java/com/google/re2j/Pattern.java index 2fd7a727..5ad502a2 100644 --- a/java/com/google/re2j/Pattern.java +++ b/java/com/google/re2j/Pattern.java @@ -36,6 +36,11 @@ public final class Pattern implements Serializable { * Flag: Unicode groups (e.g. {@code \p\ Greek\} ) will be syntax errors. */ 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; @@ -117,10 +122,10 @@ 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); } @@ -133,7 +138,7 @@ 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)); } /** diff --git a/javatests/com/google/re2j/MatcherTest.java b/javatests/com/google/re2j/MatcherTest.java index 9abc351c..b18da290 100644 --- a/javatests/com/google/re2j/MatcherTest.java +++ b/javatests/com/google/re2j/MatcherTest.java @@ -468,4 +468,21 @@ 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())); + } + } }