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,String
Classicsplit
The 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.split
The 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 package
Pattern
andMatcher
Classes 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 aMatcher
Object, 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 toparts
in 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.