Using String.split() with Multiple Delimiters
In various programming contexts, it becomes necessary to split a string based on specific delimiters to extract its constituent parts. However, when encountering multiple delimiters, we may face challenges in achieving the desired output.
Consider the following scenario: you are required to split a string using both dashes (-) and dots (.), as seen in the sample input "AA.BB-CC-DD.zip." The goal is to obtain the following result:
AA BB CC DD zip
However, a common misconception in attempting to split the string could be this code snippet:
private void getId(String pdfName) { String[] tokens = pdfName.split("-\."); }
This code is designed to match a pattern where a dash is followed by a dot, which is not what we are trying to achieve. We need to use the regex OR operator to specify that either a dash or a dot should be used as a delimiter.
String[] tokens = pdfName.split("-|\.");
By incorporating the OR operator in the regex, we instruct the split() method to consider both dashes and dots as individual delimiters. This allows for a successful split of the string, yielding the desired output:
AA
BB
CC
DD
zip
The above is the detailed content of How to Use String.split() with Multiple Delimiters in Java?. For more information, please follow other related articles on the PHP Chinese website!