• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringTokenizer not splitting properly  RSS feed

 
hemamalini nithyanandam
Ranch Hand
Posts: 53
Chrome Eclipse IDE MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a string like "|ABCSG|test123.txt|ABCSG|XYZ.JPG". i need to separate the filenames using a unique delimiter and want to display the filenames alon in front end. For the above string if i use


i am getting output as
te
t123.txt
XYZ.JP

it considers S & G also as tokens. i couldnt understand why it considers S,G also to separate. i want the full pattern |ABCSG| to split..
 
Anuj Sharma R
Greenhorn
Posts: 28
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Hema,

This should work. Can you copy the whole code snippet? Also, it should not matter but what is the java version you are using?

Thanks,
Anuj
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The bar | is a special character in reguylar expressions so you have to escape it with \\.
Also, using StringTokenizer is discouraged. Use the String.split method instead.
 
Anuj Sharma R
Greenhorn
Posts: 28
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems to work for me with or without escape sequence in Eclipse using jdk7. But, I agree with Armitage Because '|' is a meta character in regex and means OR so if you want to include '|' as a char to match then it must be escaped with a '\' BUT '\' is a meta character used for an escape in String literals so it must also be escaped. .

You also might want to check Scanner class which should help:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This has nothing to do with regexes. The delimiters argument is a set of characters that is used to split on, not a proper String. So in your example, if any |, A, B etc is encountered, that is used to split on. Either that's case insensitive, or your example isn't 100% accurate.

you should check out String.split (or in Java 8, Pattern.splitAsStream). As said, the | is a meta character that you should escape. You can also use Pattern.quote to return a regex that treats the String as a literal value.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!