regex
Split string example
This is an example of how to split a String. We will split a given String using the Pattern API. Splitting a given String implies that you should:
- Read the given input String.
- Compile a given String regular expression to a Pattern, using
compile(string regex)
API method of Pattern. The given regex in the example is the exclamation point. - Use
split(CharSequence input)
API method of Pattern to split the given input sequence around matches of this pattern. It returns an array of strings. - Use the
asList(String... a)
API method of Arrays to get a List backed by the array. - You can also use
split(CharSequence input, int limit)
API method of Pattern to split the given input sequence around matches of this pattern, using a limit parameter that controls the number of times the pattern is applied and therefore affects the length of the resulting array.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Arrays; import java.util.regex.Pattern; public class SplitDemo { public static void main(String[] args) { String input = "This!!unusual use!!of exclamation!!points"; System.out.println(Arrays.asList(Pattern.compile("!!").split(input))); // Only do the first three: System.out .println(Arrays.asList(Pattern.compile("!!").split(input, 3))); System.out.println(Arrays.asList("Aha! String has a split() built in!" .split(" "))); } }
Output:
[This, unusual use, of exclamation, points]
[This, unusual use, of exclamation!!points]
[Aha!, String, has, a, split(), built, in!]
This was an example of how to split a String in Java.