SoFunction
Updated on 2025-05-19

How to handle multiple delimiters in Java strings

If there are multiple delimiters in a string, you can use regular expressions to define the delimiters to split the string.

The following is a detailed introduction to several common treatment methods.

Method 1: Use regular expression to split strings

In Java,StringClassicsplitThe method can receive a regular expression as a separator.

You can combine multiple delimiters into a regular expression.

For example, to use spaces, commas, and semicolons as delimiters, you can use regular expressions[ ,;]

Here is the sample code:

public class SplitStringWithMultipleDelimiters {
    public static void main(String[] args) {
        String input = "apple, banana; cherry orange";
        // Use regular expression [ ,;] as the separator        String[] parts = ("[ ,;]");

        for (String part : parts) {
            if (!()) {
                (part);
            }
        }
    }
}    

Code explanation

  • ("[ ,;]")[ ,;]Is a character class regular expression that matches spaces, commas, or semicolons.splitThe method will split the string into parts based on this regular expression.
  • if (!()): Since empty strings may be generated after splitting, use this condition to filter out empty strings.

Method 2: Use Pattern and Matcher classes

You can also useIn the packagePatternandMatcherClasses manually handle segmentation logic, which is more flexible and can handle more complex situations.

Here is the sample code:

import ;
import ;
import ;
import ;

public class SplitStringWithPatternMatcher {
    public static void main(String[] args) {
        String input = "apple, banana; cherry orange";
        // Define regular expressions and match separators        Pattern pattern = ("[ ,;]");
        Matcher matcher = (input);

        List<String> parts = new ArrayList<>();
        int startIndex = 0;
        while (()) {
            int endIndex = ();
            if (endIndex > startIndex) {
                ((startIndex, endIndex));
            }
            startIndex = ();
        }
        if (startIndex < ()) {
            ((startIndex));
        }

        for (String part : parts) {
            (part);
        }
    }
}    

Code explanation

  • ("[ ,;]"): Compile a regular expression to match spaces, commas, or semicolons.
  • Matcher matcher = (input): Create aMatcherObject, used to find matching delimiters in input strings.
  • while (()): Loop to find the delimiter in the input string. After each delimiter is found, extract the substring before the delimiter and add it topartsin the list.
  • if (startIndex < ()): Processes the substring after the last delimiter.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.