The method takes a regular expression as a parameter. If you want to use a text separator, you must escape the characters \ ^ $ . | ? * + ( ) [ {by preceding them with a \.
String[] parts = string.split("\\|"); // Separar por "|"
String separador = Pattern.quote("|");
String[] parts = string.split(separador);
Having trouble using a character as a separator?
There are characters for "special use" called metacharacters ,
Metacharacters are non-alphabetic characters that have special meaning in regular expressions. What are they :
\, ^, $, ., |, ?, *, +, (, ), {, },[
If these are used directly to split a string they will not work properly, example:
String cadena = "Hola|Stackoverflow|en|español";
String[] parts = cadena.split("|");
System.out.println(Arrays.asList(parts));
Incorrect output:
[H, o, l, a, |, S, t, a, c, k, o, v, e, r, f, l, o, w, |, e, n, |, e, s, p, a, ñ, o, l]
these characters must be escaped preceding the "\" character, example:
String cadena = "Hola|Stackoverflow|en|español";
String[] parts = cadena.split("\\|");
System.out.println(Arrays.asList(parts));
Correct output:
[Hola, Stackoverflow, en, español]
In order to apply the separator in any of the cases, the following method can be used, in which the string and the separator are defined, if it detects that the separator character is a metacharacter, it applies an escape:
private static String[] separaCaracteres(String cadena, String separator){
System.out.println("Separator: " + separator);
String[] parts = null;
if(separator.equals("|")|| separator.equals("\\")||separator.equals(".")||separator.equals("^")||separator.equals("$")
||separator.equals("?")||separator.equals("*")||separator.equals("+")||separator.equals("(")||separator.equals(")")
||separator.equals("{")||separator.equals("[")){
//Es metacaracter!
parts = cadena.split("\\"+separator);
}else{
//No es metacaracter.
parts = cadena.split(separator);
}
return parts;
}
However, when using splitit we must take into account some things.
special characters
When splitting any string we must consider that this method takes a regular expression , so it will be necessary to escape the special characters when the case warrants it.
There are 12 characters with special meanings: the backslash \, the box ^, the dollar sign $, the period ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis )and the opening bracket [, the opening brace {. These special characters are often called "metacharacters". ( See this link )
So if you want to split, for example this string: período/punto, which means " any character " in regex, use the backslash \to escape the individual special character. Something like this: split("\\."), either use the character class\[\] to represent literal characters like split("[.]"), or use Pattern#quote()to escape the entire string like split(Pattern.quote (". ")).
String[] parts = string.split(Pattern.quote(".")); // Split on period.
A preliminary test can be done
To test beforehand if the string contains certain characters, use String#contains().
if (string.contains("-")) {
// Hacer split.
} else {
throw new IllegalArgumentException("String " + string + " no contiene -");
}
But this code doesn't take a regular expression. To do this, use String#matches()instead.
Preserve the division character in some of the parts
If you want to preserve the split character in the resulting parts, make use of positive appearance . In case you want to have the split character on the left side of the last split, use positive lookbehind prefixing the group ?<=in the pattern.
In case you want to have the split character at the end, on the right side of the first split, use positive lookahead prefixing the group ?=in the pattern.
This method has two variants and splits this string around the matches of the given regular expression.
The syntax of this method would be:
public String[] split(String regex)
Parameter detail:
Regex - the delimiting regular expression.
return value
Returns the array of strings computed by partitioning this string around the matches of the given regular expression.
Example
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("123-654321");
System.out.println("Return Value :" );
for (String retval: Str.split("-")) {
System.out.println(retval);
}
}
}
For that, the method is used
String#split()
in which you define a separator, which in the case of this String is"-"
.The method takes a regular expression as a parameter. If you want to use a text separator, you must escape the characters
\ ^ $ . | ? * + ( ) [ {
by preceding them with a\
.Or you can use the method
Pattern#quote()
.Having trouble using a character as a separator?
There are characters for "special use" called metacharacters ,
If these are used directly to split a string they will not work properly, example:
Incorrect output:
these characters must be escaped preceding the "\" character, example:
Correct output:
In order to apply the separator in any of the cases, the following method can be used, in which the string and the separator are defined, if it detects that the separator character is a metacharacter, it applies an escape:
Example calling the above method:
Departure:
split()
is the methodThe most appropriate method to split a string is
String#split()
.However, when using
split
it we must take into account some things.special characters
When splitting any string we must consider that this method takes a regular expression , so it will be necessary to escape the special characters when the case warrants it.
There are 12 characters with special meanings: the backslash
\
, the box^
, the dollar sign$
, the period.
, the vertical bar or pipe symbol|
, the question mark?
, the asterisk or star*
, the plus sign+
, the opening parenthesis(
, the closing parenthesis)
and the opening bracket[
, the opening brace{
. These special characters are often called "metacharacters". ( See this link )So if you want to split, for example this string:
período/punto
, which means " any character " in regex, use the backslash\
to escape the individual special character. Something like this:split("\\.")
, either use the character class\[\]
to represent literal characters likesplit("[.]")
, or usePattern#quote()
to escape the entire string likesplit(Pattern.quote (". "))
.A preliminary test can be done
To test beforehand if the string contains certain characters, use
String#contains()
.But this code doesn't take a regular expression. To do this, use
String#matches()
instead.Preserve the division character in some of the parts
If you want to preserve the split character in the resulting parts, make use of positive appearance . In case you want to have the split character on the left side of the last split, use positive lookbehind prefixing the group
?<=
in the pattern.In case you want to have the split character at the end, on the right side of the first split, use positive lookahead prefixing the group
?=
in the pattern.Limit the number of resulting parts
If you want to limit the number of resulting parts, you can supply the desired number as the second argument to the method
split()
.empty strings
There are cases where the elements of the returned String array have blank strings.
Prefix : - when the string starts with the delimiter, the first element becomes the empty string.
It is equivalent to:
Middle : - each additional occurrence of the delimiter in the middle of the String will result in a corresponding empty string:
It is equivalent to:
Suffix : all occurrences of the delimiter at the end of the string will be ignored.
It is equivalent to:
However, we can force split to count all additional delimiters at the end of the string by passing -1 as the limit:
It is equivalent to:
Sources:
Three different ways to do it:
1. Using the function
String.split()
:This solution uses regular expressions, so it's not the most efficient if you're not working with them.
2. Using the class
StringTokenizer
:The problem with this method is that it only works well when the delimiter has length 1.
3. Implement it using
String.indexOf()
:In this case it will work correctly for delimiters of any length.
Using
StringTokenizer
: in the constructor of such we specify the delimiter "-",new StringTokenizer(nombre,"-");
split() string split() method String
This method has two variants and splits this string around the matches of the given regular expression.
The syntax of this method would be:
Parameter detail:
Regex - the delimiting regular expression.
return value
Returns the array of strings computed by partitioning this string around the matches of the given regular expression.
Example
This will produce the following output:
What you can do is use the method
substring
, that is, extract certain characters by their position or range of positions.If that's not the only format you use, you can use the method
indexOf
, which will help you extract everything that comes after the hyphen.I hope it will help you, this is an example of what I did with that same chain
It is important to note that when performing the .split() the first element starts at [0]
If the result is not achieved by the separator, position [0] will be equal to the original string