I have the following lines:
valor1=cadena.split("|")[0];
valor2=cadena.split("|")[1] ;
However, I am getting null
, which means I am not getting any value when doing the split.
I have tried the same but with comma :
valor1=cadena.split(",")[0];
valor2=cadena.split(",")[1] ;
And this does work.
Hello friend I recommend you to do this:
To make a split in java using a special character ".", "$", etc... as a separation pattern, we must use the escape characters "\" as a prefix.
Code:
In your case it would be something like this:
This link will also help you:
Split method in Java
Since
split
the class methodjava.lang.String
first receives a regular expression, the|
(unescaped) character is considered to be an alternation operator . 1❍ No exhaust
❍ With exhaust
Hence it is necessary to escape the
|
with\
. Namely:❍ No limit
However, it may be more convenient to specify the limit. For example, with no limit specified:
❍ With limit (
-1
)Grades
You have to use
The method
split(String regex)
uses a regular expression, so you have to escape the|
, or you separate by "nothing or nothing".You can store the elements separated by the pipe in an array
|
using .split("\\|") :or via .split(Pattern.quote("|")) :
to get your values
You can also get the string values directly like this:
or by
.split(Pattern.quote("|"))
:Unlike :
which can be done without escaping the character
","
since it is not a special character.I would recommend you replace your "\" with "," with the replace java.lang.String method, leaving something like this:
Or do it as indicated above.