| Author |
splitting a string with multiple delimiters
|
ash chowdary
Greenhorn
Joined: Apr 23, 2009
Posts: 16
|
|
hi all,
how to split a string based on multiple delimiting characters.
for example i have these delimiters in string array---->String[] sep_list = { " ", "\n","[","]","{","}","(",")"};
how can we split it in one go...
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
String.split takes a regular expression. Take a look at the API of java.util.regex.Pattern to see what this pattern can look like. You can read there how to get a "choice" pattern.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Mikko Kohtamäki
Ranch Hand
Joined: Dec 13, 2008
Posts: 112
|
|
First I would replace
String[] sep_list = { " ", "\n","[","]","{","}","(",")"};
with
Character[] sep_list = { ' ', '\n', '[', ']', '{', '}', '(', ')' };
or not
Then look at java.util.regex.Pattern class, it has static method called quote(String) and it returns "A literal string replacement"
Now you call it like Pattern.quote(sep_list[someIndex].toString()) and add it to your pattern. Strings in pattern are separated with [] characters
and all of them are surrounded with [] characters too. Example [[string][string]]
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
I don't understand all of that last posting. Are you sure about [] pairs? It is worthwhile looking through the Java™ Tutorials where there is a very good introduction to regular expressions.
|
 |
Mikko Kohtamäki
Ranch Hand
Joined: Dec 13, 2008
Posts: 112
|
|
OK sorry, here is complete example. This is first time when I did this too.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Mikko Kohtamäki wrote:
You don't need those [ and ] inside the loop; [abc] work just fine without having to writen [[a][b][c]]. And you don't need the inner [] for escaping because that's what the Pattern.quote will do.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
So that's what the [] meant.
Thank you.
|
 |
Mikko Kohtamäki
Ranch Hand
Joined: Dec 13, 2008
Posts: 112
|
|
Yes no need for [] characters inside the loop. I did not realize the meaning of quote word , thanks for correcting me Rob. In my first post I did try to explain it first but failed though
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Mikko Kohtamäki wrote: . . , thanks . . .
|
 |
 |
|
|
subject: splitting a string with multiple delimiters
|
|
|