You can split a [String](<https://docs.oracle.com/javase/8/docs/api/java/lang/String.html>)
on a particular delimiting character or a Regular Expression, you can use the [String.split()](<https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String->)
method that has the following signature:
public String[] split(String regex)
Note that delimiting character or regular expression gets removed from the resulting String Array.
Example using delimiting character:
String lineFromCsvFile = "Mickey;Bolton;12345;121216";
String[] dataCells = lineFromCsvFile.split(";");
// Result is dataCells = { "Mickey", "Bolton", "12345", "121216"};
Example using regular expression:
String lineFromInput = "What do you need from me?";
String[] words = lineFromInput.split("\\\\s+"); // one or more space chars
// Result is words = {"What", "do", "you", "need", "from", "me?"};
You can even directly split a String
literal:
String[] firstNames = "Mickey, Frank, Alicia, Tom".split(", ");
// Result is firstNames = {"Mickey", "Frank", "Alicia", "Tom"};
Warning: Do not forget that the parameter is always treated as a regular expression.
"aaa.bbb".split("."); // This returns an empty array
In the previous example .
is treated as the regular expression wildcard that matches any character, and since every character is a delimiter, the result is an empty array.
Splitting based on a delimiter which is a regex meta-character
The following characters are considered special (aka meta-characters) in regex
< > - = ! ( ) [ ] { } \\ ^ $ | ? * + .
To split a string based on one of the above delimiters, you need to either escape them using \\\\
or use Pattern.quote()
:
Pattern.quote()
:String s = "a|b|c";
String regex = Pattern.quote("|");
String[] arr = s.split(regex);