2013-11-09 20:16:22 +00:00
|
|
|
import regex.Matcher;
|
|
|
|
import regex.Pattern;
|
|
|
|
|
|
|
|
public class Regex {
|
|
|
|
private static void expect(boolean v) {
|
|
|
|
if (! v) throw new RuntimeException();
|
|
|
|
}
|
|
|
|
|
|
|
|
private static Matcher getMatcher(String regex, String string) {
|
|
|
|
return Pattern.compile(regex).matcher(string);
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void expectMatch(String regex, String string) {
|
|
|
|
expect(getMatcher(regex, string).matches());
|
|
|
|
}
|
|
|
|
|
|
|
|
private static void expectNoMatch(String regex, String string) {
|
|
|
|
expect(!getMatcher(regex, string).matches());
|
|
|
|
}
|
|
|
|
|
2013-11-11 15:29:24 +00:00
|
|
|
private static void expectGroups(String regex, String string,
|
|
|
|
String... groups) {
|
|
|
|
Matcher matcher = getMatcher(regex, string);
|
|
|
|
expect(matcher.matches());
|
|
|
|
expect(matcher.groupCount() == groups.length);
|
|
|
|
for (int i = 1; i <= groups.length; ++i) {
|
2013-11-10 16:02:18 +00:00
|
|
|
if (groups[i - 1] == null) {
|
|
|
|
expect(matcher.group(i) == null);
|
|
|
|
} else {
|
|
|
|
expect(groups[i - 1].equals(matcher.group(i)));
|
|
|
|
}
|
2013-11-11 15:29:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-11-13 23:54:47 +00:00
|
|
|
private static void expectFind(String regex, String string,
|
|
|
|
String... matches)
|
|
|
|
{
|
|
|
|
Matcher matcher = getMatcher(regex, string);
|
|
|
|
int i = 0;
|
|
|
|
while (i < matches.length) {
|
|
|
|
expect(matcher.find());
|
|
|
|
expect(matches[i++].equals(matcher.group()));
|
|
|
|
}
|
|
|
|
expect(!matcher.find());
|
|
|
|
}
|
|
|
|
|
2013-11-09 20:16:22 +00:00
|
|
|
public static void main(String[] args) {
|
|
|
|
expectMatch("a(bb)?a", "abba");
|
|
|
|
expectNoMatch("a(bb)?a", "abbba");
|
|
|
|
expectNoMatch("a(bb)?a", "abbaa");
|
2013-11-11 15:29:24 +00:00
|
|
|
expectGroups("a(a*?)(a?)(a??)(a+)(a*)a", "aaaaaa", "", "a", "", "aaa", "");
|
2013-11-14 17:13:12 +00:00
|
|
|
expectMatch("...", "abc");
|
|
|
|
expectNoMatch(".", "\n");
|
2013-11-10 16:02:18 +00:00
|
|
|
expectGroups("a(bb)*a", "abbbba", "bb");
|
|
|
|
expectGroups("a(bb)?(bb)+a", "abba", null, "bb");
|
2013-11-13 23:54:47 +00:00
|
|
|
expectFind(" +", "Hello , world! ", " ", " ", " ");
|
2013-11-09 21:43:26 +00:00
|
|
|
expectMatch("[0-9A-Fa-f]+", "08ef");
|
|
|
|
expectNoMatch("[0-9A-Fa-f]+", "08@ef");
|
2013-11-12 17:34:30 +00:00
|
|
|
expectGroups("(?:a)", "a");
|
2013-11-12 05:09:25 +00:00
|
|
|
expectGroups("a|(b|c)", "a", (String)null);
|
|
|
|
expectGroups("a|(b|c)", "c", "c");
|
2013-11-12 15:33:45 +00:00
|
|
|
expectGroups("(?=a)a", "a");
|
2013-11-14 17:10:18 +00:00
|
|
|
expectGroups(".*(o)(?<=[A-Z][a-z]*)", "Hello", "o");
|
2013-11-20 15:57:04 +00:00
|
|
|
expectNoMatch("(?!a).", "a");
|
2013-11-09 20:16:22 +00:00
|
|
|
}
|
|
|
|
}
|