DEV Community

Dash One
Dash One

Posted on

String Manipulation Tricks (Day 1)

(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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

StringFormat performs well compared to Java regex. And to me it's more readable.

What do you think?

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️