Is a formatted string still a string? Is it still printable, or it is just a bunch of rules?

108 Views Asked by At

I am looking at other code on a Java practice. Here is his code:

import java.util.Arrays;
import java.util.stream.Collectors;

public class StripComments {

    public static String stripComments(String text, String[] commentSymbols) {
        String pattern = String.format(
                "[ ]*([%s].*)?$",
                Arrays.stream( commentSymbols ).collect( Collectors.joining() )
        );
        return Arrays.stream( text.split( "\n" ) )
                .map( x -> x.replaceAll( pattern, "" ) )
                .collect( Collectors.joining( "\n" ) );
    }

}

In his code, the pattern is representing something after whatever in the commentSymbols, right? If I decide to print the pattern right after the string creation, what would the pattern be like? If pattern is a printable string, why in the later sentence we can use it to filter out the sentence we want to delete?

I used debug mode and it showed pattern looks like this "[ ]*([#!].*)?$" while the inputs are ("apples, pears # and bananas\ngrapes\nbananas !apples", new String[]{"#", "!"}). Does this string have any meaning? If I just initialize a new string and assign this value "[ ]*([#!].*)?$" to it, would it work same?

2

There are 2 best solutions below

3
ash On

It helps to break down the steps in the code. There is a lot in that example packed into a small space.

The x -> x.replaceAll( pattern, "" ) expression is calling the replaceAll method on a string named x. If you look at that method definition, you will see how the regular expression, [ ]*([#!].*)?$, is used. Yes, that regular expression is being passed in as a String.

And, yes, if you hard-code the same string and pass it to replaceAll it will produce the same result.

The Arrays.stream() call is using minimal syntax to iterate over the elements of the array commentSymbols. If you look up the Collectors.joining() method call, you will find that concatenates all of the strings it is fed. So if you input 2 strings, "a" and "b", it will end up producing a single String, "ab".

Then the return value of Arrays.stream() is passed to String.format where the %s in the first, format, argument is replaced with that value.

0
Minsu Kim On

Yes, the two patterns you provided are functionally equivalent. Both patterns, [ ]*([%s].*)?$ and [ ]*([#!].*)?$, serve the same purpose in the context of the stripComments method. They are designed to match and remove any characters following the specified comment symbols (# and ! in this case) until the end of the line.

The %s in the first pattern is a placeholder for the characters in the commentSymbols array, and when you substitute it with actual values using String.format, it becomes [ ]*([#!].*)?$, which is the same as the second pattern.

So, both patterns are equivalent and will produce the same result when used in the stripComments method for the given input.