Skip to content

Readable String Manipulation with Google Mug

Ben Yu edited this page Apr 7, 2024 · 14 revisions

This library provides easy-to-read string manipulation utils. Some examples:

Match and Extract

new StringFormat("/{user}-home/{year}/{month}/{day}")
    .parse(path, (user, year, month, day) -> ...);

Scan and Collect

// Returns Map.of("k1", "v1", "k2", "v2")
Map<String, String> keyValues =
    new StringFormat("[{key}:{value}]")
        .scanAndCollectFrom("I have [k1:v1] and [k2:v2] etc.", Collectors::toMap);

Replace

// replace file extension name
Substring.last('.').toEnd().replaceFrom(filename, ".yaml");

Remove

// remove the scheme from a url
Substring.upToIncluding(first("://")).removeFrom(url);

Parse a date time string (no pattern string required)

// Parse the datetime string read from a file
List<String> lines = readLinesFromTestFile(...);
StringFormat lineFormat =
    new StringFormat("{time}, {event_id}, {event_type}");
lines.stream()
    .map(line -> lineFormat.parseOrThrow(line, (time, id, type) -> {
      ZonedDateTime dateTime = DateTimeFormats.parseZonedDateTime(time);
      ...
    });

See javadoc for details.

Omitted, but other useful utils including BiStream for streaming pairs, Optionals etc.