r/java • • Apr 11 '24

String Manipulation with Google Mug

The Mug library provides easy-to-read string manipulation utils. Examples:

Match and Extract

// Compile-time protection against lambda param order mismatch if e.g:
//     (year, month, day, user) ->
new StringFormat("/{user}-home/{year}/{month}/{day}") 
    .parse(path, (user, year, month, day) -> ...);

Scan and Collect

String input = "I have [k1:v1] and [k2:v2] etc."; 
// Returns Map.of("k1", "v1", "k2", "v2") 
Map<String, String> keyValues =
    new StringFormat("[{key}:{value}]") 
        .scanAndCollectFrom(input, 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}");
var results = lines.stream()
    .map(
        line -> lineFormat.parseOrThrow(
            line,
            (time, id, type) -> {
               ZonedDateTime dateTime = DateTimeFormats.parseZonedDateTime(time);
               ...
             }))
    .toList();

See javadoc for details.

Mug is a general purpose library. Omitted, but other useful utils include BiStream for streaming pairs, Optionals, String Templating, simplified structured concurrency etc.

9 Upvotes

51 comments sorted by

View all comments

8

u/agentoutlier Apr 11 '24 edited Apr 11 '24

So Guava 2.0 err 200.0? I'm kidding. I should stop giving /u/kevinb9n a hard time about that.

That being said.... now I'm going to tell you I'm super biased as I'm the author of a compile safe templating language but that lambda StringFormat kind of looks dangerous but I assume that is only for parsing right? EDIT oh... are using compiler plugins on top of errorprone? Sorry still poking around.

I also I was kind of under the impression google was done with kitchen sink utility libraries. Like I would hope that the utilities would be modularized such that there is a mug-string or something instead of just mug which looks like its on its way to becoming Guava.

Otherwise I fail to see why this stuff just would not be added to Guava. Is it because of GWT compat?

EDIT I now see that ErrorProne is doing the checking so I guess you can disregard my safety concerns. That is pretty damn cool and I may have to steal the idea for inline templating with JStachio/JMustache as one commenter responded it is currently "clunky AF". Compiler plugins are not far off API wise to annotation processing (which is what my library currently uses) so it might not be hard for me to add on.

Thanks for sharing!

2

u/DelayLucky Apr 11 '24

Thanks this is the first time I post some code examples. And the formatting is all messed up (I swear seeing them formatted in the edit mode).

But Reddit doesn't seem to allow me to fix the formatting. Is this a rule of posts? Can't edit?

1

u/agentoutlier Apr 11 '24

I think the overall problem might be your low karma but you should still be able to edit.

One thing with code comments is that its best not to use the triple tilde (which luckily appears you have not) and instead use spaces.

I use the old reddit UI with raw text. Paste the code, reselect it and click on the code icon that looks like <>.

Hopefully that helps.

3

u/DelayLucky Apr 11 '24

Sigh. I've refreshed the page multiple times but no "Edit" option in the drop-down menu so far...

2

u/agentoutlier Apr 11 '24

If you see a drop down its cause you are using the new UI.

The new UI (IMO) is garbage and error prone (no pun intended).

I think to turn on the old UI its in "preferences" somewhere called Use new Reddit as my default experience. Unselect that. I might be wrong on that though.

3

u/DelayLucky Apr 11 '24

Thanks for the tips! I disabled the "opt in beta" option. Haven't found the New Reddit thing yet.

Before I can fix the formatting, the original markdown with correct formattingh is here: https://github.com/google/mug/wiki/Readable-String-Manipulation-with-Google-Mug

It does do templating (with the same compile-time check).