wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes How to use String.split with Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to use String.split with "[" separator?" Watch "How to use String.split with "[" separator?" New topic
Author

How to use String.split with "[" separator?

Rogerio Kioshi
Ranch Hand

Joined: Apr 12, 2005
Posts: 689
Hello,

If I have a string like this:
String str="AAAA[BBB[CCC";

And I want to split it in an array:
item[0]="AAAA"
item[1]="BBB"
item[2]="CCC"

How do I do it?

I'm trying
String item[]=str.split("[")

but it's not working...

Seems to be very simple but I don't know. Very shamed!


SCEA 5 (part 1), SCBCD, SCWCD, SCJP, CLP, CLS
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18875
    
  40

Try...



Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rogerio Kioshi
Ranch Hand

Joined: Apr 12, 2005
Posts: 689
Thank you.

(Javadoc API 5 does not explain this very well...)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Yes it does.

The 1-argument split method links both to the 2-argument split method and Pattern. Moreover, the 2-argument split method not only links to Pattern, but to Pattern.compile in particular. On the first line there's a link to the regular expression summary.

On that last page (part of Pattern), it is clearly mentioned that:
a) [ is used with ] for a set
b) \ is used as escape character, and needs to be duplicated

Now clearly, after seeing just "[" fail, you could have tried it with "\\[" ?


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: How to use String.split with "[" separator?