Reputation: 4452
I hava a string(A list of author names for a book) which is of the following format:
author_name1
, author_name2
, author_name3
and author_name4
How can I parse the string so that I get the list of author names as an array of String
. (The delimiters in this case are ,
and the word and
. I'm not sure how I can split the string based on these delimiters (since the delimiter here is a word and not a single character).
Upvotes: 1
Views: 287
Reputation: 8451
I think you need to include the regex OR operator:
String[]tokens = someString.split(",|and");
Upvotes: 0
Reputation: 55589
Try:
yourString.split("\\s*(,|and)\\s*")
\\s*
means zero or more whitespace characters (so the surrounding spaces aren't included in your split).
(,|and)
means ,
or and
.
Test (Arrays.toString
prints the array in the form - [element1, element2, ..., elementN]
).
Upvotes: 2
Reputation: 14439
You should use regular expressions:
"someString".split("(,|and)")
Upvotes: 7