1

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).

Raj
  • 4,192
  • 9
  • 37
  • 44
  • 2
    http://stackoverflow.com/questions/5993779/java-use-split-with-multiple-delimiters – rags Jul 01 '13 at 08:35

4 Answers4

7

You can use myString.split(",|and") it will do what you want :)

C4stor
  • 7,995
  • 4
  • 28
  • 46
7

You should use regular expressions:

"someString".split("(,|and)")
michael nesterenko
  • 13,742
  • 23
  • 107
  • 178
2

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]).

Java regex reference.

Bernhard Barker
  • 52,963
  • 14
  • 96
  • 130
0

I think you need to include the regex OR operator:

String[]tokens = someString.split(",|and");
Vijay
  • 7,651
  • 9
  • 41
  • 69