backslash-dot is invalid because Java doesn't need to escape the dot. You've got to escape the escape character to get it as far as the regex which is used to split the string.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
split (separator, limit) , if the separator is not in the string, it returns a one-element array with the original string in it.
To split a string with dot, use the split() method in Java. str. split("[.]", 0);
String.split()
takes in regex as argument and $
is a metacharacter in Java regex API
. Therefore, you need to escape it:
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("\\$")[i]);
}
Other metacharacters supported by the Java regex API
are: <([{\^-=!|]})?*+.>
split(Pattern.quote("$"))
Is my favorite.
See Pattern#quote
:
Returns a literal pattern String for the specified String.
Your code doesn't work because $
has a special meaning in regex, and since String#split
takes a regex as an argument, the $
is not interpreted as the String "$"
, but as the special meta character $
.
Escape it. the split()
method takes a regex: split("\\$")
try something like this
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("$")[i]);
}
NOTE: split()
uses a regular expression.
Your regular expression uses a special character ie $
$
is the regular expression for "end of line".
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.length;i++){
System.out.println("Now you GOT this :: "+split(Pattern.quote("$")));
}
There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., 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 square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
So your $
is also metacharacter
as defination says so you can't split using simple function. Though you must use pattern
in this case.
Thanks..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With