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?
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 thereplaceAllmethod on a string namedx. 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
replaceAllit will produce the same result.The
Arrays.stream()call is using minimal syntax to iterate over the elements of the arraycommentSymbols. If you look up theCollectors.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 toString.formatwhere the%sin the first, format, argument is replaced with that value.