Raj
Raj

Reputation: 4452

Splitting a string in java where the delimiter is a word

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

Answers (4)

Vijay
Vijay

Reputation: 8451

I think you need to include the regex OR operator:

String[]tokens = someString.split(",|and");

Upvotes: 0

Bernhard Barker
Bernhard Barker

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

Java regex reference.

Upvotes: 2

C4stor
C4stor

Reputation: 8026

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

Upvotes: 7

michael nesterenko
michael nesterenko

Reputation: 14439

You should use regular expressions:

"someString".split("(,|and)")

Upvotes: 7

Related Questions