Search

Dark theme | Light theme
Showing posts with label JavaJoy:String. Show all posts
Showing posts with label JavaJoy:String. Show all posts

March 11, 2021

Java Joy: Formatting A String Value With Formatted Method

Java 15 introduced the multi-line string value referred to as a text block. With this introduction also the formatted method was added to the String class. The method can be invoked on a String value directly and function exactly as the static String.format method. The nice thing is that now we directly can use a method on the value instead of having to use a static method where the value is passed as argument.

In the following example we use the formatted method for a normal String value and a text block:

package mrhaki.string;

public class Formatted {
    public static void main(String[] args) {
        String text = "Hi, %s, thank you for reading %d blogs".formatted("mrhaki", 2);
        assert "Hi, mrhaki, thank you for reading 2 blogs".equals(text);

        String email = """
        Hello %s,

        thank you for reading %d blogs.
        """.formatted("Hubert", 2);

        assert """
                Hello Hubert,

                thank you for reading 2 blogs.
                """.equals(email);
    }
}

Written with Java 15.

April 11, 2020

Java Joy: Using Functions To Replace Values In Strings

Since Java 9 we can use a function as argument for the Matcher.replaceAll method. The function is invoked with a single argument of type MatchResult and must return a String value. The MatchResult object contains a found match we can get using the group method. If there are capturing groups in the regular expression used for replacing a value we can use group method with the capturing group index as argument.

In the following example we use the replaceAll method and we use a regular expression without and with capturing groups:

package mrhaki.pattern;

import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Replace {
    public static void main(String[] args) {
        // Define a pattern to find text between brackets.
        Pattern admonition = Pattern.compile("\\[\\w+\\]");
        
        // Sample text.
        String text = "[note] Pay attention. [info] Read more.";
        
        // Function to turn a found result for regular expression to upper case.
        Function<MatchResult, String> bigAdmonition = match -> match.group().toUpperCase();
        
        assert admonition.matcher(text).replaceAll(bigAdmonition).equals("[NOTE] Pay attention. [INFO] Read more.");

        
        // Pattern for capturing numbers from string like: run20=390ms.
        Pattern boundaries = Pattern.compile("run(\\d+)=(\\d+)ms");

        // Function to calculate seconds from milliseconds.
        Function<MatchResult, String> runResult = match -> {
            double time = Double.parseDouble(match.group(2));
            return "Execution " + match.group(1) + " took " + (time / 1000) + " seconds.";
        };

        assert boundaries.matcher("run20=390ms").replaceAll(runResult).equals("Execution 20 took 0.39 seconds.");
    }
}

Written with Java 14.