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,342
  • 9
  • 40
  • 45
  • 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
  • 8,355
  • 6
  • 29
  • 47
7

You should use regular expressions:

"someString".split("(,|and)")
michael nesterenko
  • 14,222
  • 25
  • 114
  • 182
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
  • 54,589
  • 14
  • 104
  • 138
0

I think you need to include the regex OR operator:

String[]tokens = someString.split(",|and");
Vijay
  • 8,131
  • 11
  • 43
  • 69