I have such data in a flat text file,
"
106083|1791||7|73755|48|96|3||01/07/2005 13:04:48.979215 PST|||||t|f||
t|f|t|"
"
And such java code to read this line and split it by "|",
"
while ((( rd = in.readLine())!= null)) {
String delimiter = new String(''|")
String[] t1 = rd.split(delimiter);
String[] t2 = rd.split("|");
}
"
Either way, the split does not work! It splits the string per each
char. Does someone know why ?
Here is my jdk information on the linux box.
"
java version "1.6.0"
Java(TM) SE Runtime Environment (build 1.6.0-b105)
Java HotSpot(TM) Server VM (build 1.6.0-b105, mixed mode)
"
Thanks a lot for any tips.
Chun
`split' uses a regex command, and '|' happens to be a special operator
in regex. Instead of "|", you want "\\|".
> Either way, the split does not work! It splits the string per each
> char. Does someone know why ?
Your regex specifies either the empty string or the empty string. Since
there is an empty string between each character, the string is split
between each character. It's what you told it do.
For more information:
<http://java.sun.com/javase/6/docs/api/java/lang/String.html> and
<http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html>
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
Please ignore that, "\\|" works for me, I guess I use perl too much
-:)
-cji
Because the argument to split() is a regex not a string.
In regexes, certain characters (metacharacters) have special meanings.
The vertical bar is such a metacharacter, representing alternation.
public class MetaChar {
public static void main(String[] args) {
String s = "oneXtwoYthreeXfour";
String[] a = s.split("X|Y");
for (String w:a)
System.out.println(w);
}
}
You have to "escape" the vertical bar if you want to treat it as an
ordinary character and not as a metacharacter.
http://www.regular-expressions.info/alternation.html
http://www.regular-expressions.info/characters.html
>Either way, the split does not work! It splits the string per each
>char. Does someone know why ?
you mean literal | not the regex command |. See
http://mindprod.com/jgloss/regex.html
on quoting.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
> String delimiter = new String(''|")
there is no need for new String.
See http://mindprod.com/jgloss/newbie.html
you can write that;
String delimiter = ''|";
but of course as others pointed out, you meant:
String delimiter = ''\\|";