Split a String by Comma and Space in Java
This code demonstrates how to split a string by comma and space characters in Java:
String SPLIT_PATTERN = "(\\s+,\\s+)|(\\s+,)|(,\\s+)|,|(\\s+)"; String text = "email@example.com,firstname.lastname@example.org, email@example.com, firstname.lastname@example.org"; String output = text.split(SPLIT_PATTERN); System.out.println(Arrays.toString(output)); System.out.println("Total elements : " + output.length);
In the given code, there is a string variable named "text" that contains a series of email addresses separated by commas and spaces. The goal is to split this string into individual email addresses and store them in an array.
The line "String splitedTextArray = text.split("(\\s+,\\s+)|(\\s+,)|(,\\s+)|,|(\\s+)");" performs the split operation. It uses a regular expression pattern as the parameter to the split() method. The pattern (\\s+,\\s+)|(\\s+,)|(,\\s+)|,|(\\s+) matches various combinations of spaces and commas to identify the separation points. This pattern covers scenarios where there are spaces before or after a comma, spaces only, or commas only. The split() method divides the string based on these patterns and stores the resulting substrings into an array named splitedTextArray.
The next two lines of code print the output to the console. The first line displays the array containing the individual email addresses by converting it to a string representation using Arrays.toString(). The second line prints the total number of elements in the array, which corresponds to the number of email addresses extracted from the original string.
Overall, this code snippet demonstrates how to split a string containing email addresses using commas and spaces as separators, and then it provides the resulting email addresses as separate elements in an array.
Then ouput of the above code is as follows:
[email@example.com, firstname.lastname@example.org, email@example.com, firstname.lastname@example.org] Total elements : 4