Bottlecaps
Bottlecaps

Reputation: 129

Using multiple delimiters for .split in Java

Right now my code only separates words by white space, but I also want to separate by '.' and "," too. Here is my current code:

for (String words : input.split("\\s+"))

For example, if the user entered "bread,milk,eggs" or "Um...awkss" It would consider that one word, and I want each word to be it's own word.

And while I'm here, I can't get

input.isAlpha() 

to work either.

Upvotes: 5

Views: 13152

Answers (3)

Dariusz
Dariusz

Reputation: 22311

You can split using this regex

input.split("\\s+|.+|,+")

or simply:

input.split("[\\s.,]+")

Remember that a dot doesn't have to be escaped inside square brackets

Upvotes: 8

UMESH0492
UMESH0492

Reputation: 1731

You can use this

mySring = "abc==abc++abc==bc++abc";
String[] splitString = myString.split("\\W+");

Regular expression \W+ ---> it will split the string based upon non-word character.

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 209132

Use brackets

for (String words : input.split("[\\s.,]+"))

Brackets are used when you want any of the characters in the brackets, the + means the characters can be combined one or more times. to create one single delimiter, i.e. space and period or comma and space.

Upvotes: 5

Related Questions