Skip to content

Instantly share code, notes, and snippets.

@JayRaparla
Forked from rhyskeepence/Regex.java
Created January 15, 2017 00:43
Show Gist options
  • Save JayRaparla/877268f46c57601f30650e79bb2c8314 to your computer and use it in GitHub Desktop.
Save JayRaparla/877268f46c57601f30650e79bb2c8314 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