Skip to content

Instantly share code, notes, and snippets.

@keesun
Created August 7, 2012 09:53
Show Gist options
  • Save keesun/3284089 to your computer and use it in GitHub Desktop.
Save keesun/3284089 to your computer and use it in GitHub Desktop.
Fucking Java Matcher & String class. Please add this method to String class.
/**
* @author Keesun Baik
*/
public class RegexUtils {
public static String[] match(String input, String regexp) {
Matcher matcher = Pattern.compile(regexp).matcher(input);
String[] results = new String[matcher.groupCount() + 1];
while (matcher.find()) {
for(int i = 0 ; i < results.length ; i++) {
results[i] = matcher.group(i);
}
}
return results;
}
}
/**
* @author Keesun Baik
*/
public class RegexUtilsTest {
@Test
public void match() {
String regexp = "([^:]+):([0-9]+)?(\\+)?:([^:]+)?:?([\\s\\S]*)?";
String input = "111:222+:444:555";
String[] results = RegexUtils.match(input, regexp);
assertThat(results.length, is(6));
assertThat(results[0], is(input));
assertThat(results[1], is("111"));
assertThat(results[2], is("222"));
assertThat(results[3], is("+"));
assertThat(results[4], is("444"));
assertThat(results[5], is("555"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment