Home > Java > javaTutorial > How to Split a String Using Multiple Delimiters in Java?

How to Split a String Using Multiple Delimiters in Java?

Barbara Streisand
Release: 2024-11-25 17:45:16
Original
380 people have browsed it

How to Split a String Using Multiple Delimiters in Java?

Splitting Strings with Multiple Delimiters Using String.split()

When working with strings that contain multiple delimiter characters, it becomes necessary to specify them explicitly to achieve desired splitting behavior.

In your case, the goal is to split a string based on both the "-" and "." delimiters. However, the code provided only includes "-.", which will match only when both characters are present together.

The Solution

To correctly split on either "-" or ".", it is necessary to use the regex OR operator, denoted by "|". The updated code should be:

String[] tokens = pdfName.split("-|\.");
Copy after login

With this modification, the regular expression searches for either "-" or "." in the string, resulting in the desired output:

AA.BB-CC-DD.zip ->

AA
BB
CC
DD
zip 
Copy after login

The above is the detailed content of How to Split a String Using 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