Forem

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?

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay