Skip to content

Instantly share code, notes, and snippets.

@rhyskeepence
Created March 28, 2012 14:03
Show Gist options
  • Save rhyskeepence/2226436 to your computer and use it in GitHub Desktop.
Save rhyskeepence/2226436 to your computer and use it in GitHub Desktop.
Simplify the insanity of Regex in Java
import com.googlecode.totallylazy.Callable1;
import com.googlecode.totallylazy.Option;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.googlecode.totallylazy.Option.none;
import static com.googlecode.totallylazy.Option.some;
import static com.googlecode.totallylazy.numbers.Numbers.range;
public class Regex {
private final String pattern;
public Regex(String pattern) {
this.pattern = pattern;
}
public boolean matches(String source) {
return match(source).matches();
}
public Option<String> findIn(String source) {
Matcher matcher = match(source);
if (matcher.find()) {
return some(matcher.group(0));
} else {
return none();
}
}
public Option<Iterable<String>> findGroupsIn(String source) {
Matcher matcher = match(source);
if (matcher.find()) {
Iterable<String> matches = range(1, matcher.groupCount() + 1).map(getGroupFrom(matcher));
return some(matches);
} else {
return none();
}
}
public Option<String> findFirstGroupIn(String source) {
Matcher matcher = match(source);
if (matcher.find() && matcher.groupCount() > 0) {
return some(matcher.group(1));
} else {
return none();
}
}
private Matcher match(String source) {
return Pattern.compile(pattern).matcher(source);
}
private Callable1<Number, String> getGroupFrom(final Matcher matcher) {
return new Callable1<Number, String>() {
public String call(Number number) {
return matcher.group(number.intValue());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment