(First post. Don't know what to blog about. I'll start by recording some random coding thought whenever they occur to me and I happen to have time to write it down)
I've recently been thinking about Java string manipulation. Then I stumbled upon this string parsing code:
private static final Pattern THE_NUMBER =
    Pattern.compile("^\\s\\(([1-9][0-9]*)\\)$");
// Find the number from string with header.
// example: parseTheNumber("foo", "foo (123)") -> 123
//          parseTheNumber("foo", "bar (123)") -> empty
//          parseTheNumber("foo", "foo (str)") -> empty
Optional<Integer> parseTheNumber(String header, String string) {
  if (!string.startsWith(header)) {
    return Optional.empty();
  }
  Matcher matcher = THE_NUMBER.matcher(
      string.substring(header.length()));
  try {
    return matcher.matches()
        ? Optional.of(Integer.parseInt(matcher.group(1)))
        : Optional.empty();
  } catch (NumberFormatException e) {
    return Optional.empty();
  }
}
As a racist against Java Regex, I can't help wanting to try it out without regex (using Guava and Mug, my all-in-one toolbox).
import com.google.common.primitives.Ints;
import com.google.mu.util.StringFormat;
private static final StringFormat THE_NUMBER =
    new StringFormat("{type} ({num})");
Optional<Integer> parseTheNumber(String header, String string) {
  // StringFormat.parse() will return empty()
  //     if failed to parse, or if the lambda returns null
  return THE_NUMBER.parse(
      string,
      // Ints.tryParse() returns null if failed to parse
      (type, num) -> type.equals(header) ? Ints.tryParse(num) : null);
}
StringFormat performs well compared to Java regex. And to me it's more readable.
What do you think?
 

 
    
Top comments (0)