Home > Java > javaTutorial > How to Use String.split() with Multiple Delimiters in Java?

How to Use String.split() with Multiple Delimiters in Java?

Susan Sarandon
Release: 2024-11-25 20:45:15
Original
856 people have browsed it

How to Use String.split() with Multiple Delimiters in Java?

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
Copy after login

However, a common misconception in attempting to split the string could be this code snippet:

private void getId(String pdfName) {
    String[] tokens = pdfName.split("-\.");
}
Copy after login

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("-|\.");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template