I have following data:
1||1||Abdul-Jabbar||Karim||1996||1974
I want to delimit the tokens.
Here the delimiter is "||"
.
My delimiter setter is:
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\"" + "\\" + c[0] + "\\" + c[1] + "\"";
System.out.println("Delimiter string is: " + this.delimiter);
}
However,
String[] tokens = line.split(delimiter);
is not giving the required result.
There is something wrong in your setDelimiter()
function. You don't want to double quote the delimiters, do you?
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\\" + c[0] + "\\" + c[1];
System.out.println("Delimiter string is: " + this.delimiter);
}
However, as other users have said, it's better to use the Pattern.quote() method to escape your delimiter if your requirements permit.
Split uses regex, and the pipe char |
has special meaning in regex, so you need to escape it. There are a few ways to do this, but here's the simplest:
String[] tokens = line.split("\\|\\|");
Pipe (|) is a special character in regex. to escape it, you need to prefix it with backslash (\). But in java, backslash is also an escape character. so again you need to escape it with another backslash. So your regex should be \\|\\|
e.g,
String[] tokens = myString.split("\\|\\|");
Use the Pattern#quote()
method for escaping ||
. Try:
final String[] tokens = myString.split(Pattern.quote("||"));
This is required because |
is an alternation character and hence gains a special meaning when passed to split
call (basically the argument to split
is a regular expression in string form).
StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
"||");
while(st.hasMoreTokens()){
System.out.println(st.nextElement());
}
Answer will print
1 1 Abdul-Jabbar Karim 1996 1974
Double quotes are interpreted as literals in regex; they are not special characters. You are trying to match a literal "||"
.
Just use Pattern.quote(delimiter)
:
As requested, here's a line of code (same as Sanjay's)
final String[] tokens = line.split(Pattern.quote(delimiter));
If that doesn't work, you're not passing in the correct delimiter.
String[] splitArray = subjectString.split("\\|\\|");
You use a function:
public String[] stringSplit(String string){
String[] splitArray = string.split("\\|\\|");
return splitArray;
}
String[] strArray= str.split(Pattern.quote("||"));
where
The problem is because you are adding quotes to your delimiter. It should be removed, and it will work fine.
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\\" + c[0] + "\\" + c[1];
System.out.println("Delimiter string is: " + this.delimiter);
}
Source: Stackoverflow.com