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

How to Split a String Using Multiple Delimiters in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-25 17:45:16364browse

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

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 

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!

Statement:
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