5

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.

Bottlecaps
  • 129
  • 1
  • 2
  • 10
  • The canonical list of regular expressions you can use is at http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html - it's not a tutorial, but there are plenty of other tutorials around. – Dawood ibn Kareem Nov 14 '13 at 01:56
  • `isAlpha` is C. In Java it's called `isLetter`. Read http://www.java2s.com/Tutorial/Java/0120__Development/ChecksiftheStringcontainsonlyunicodeletters.htm – Dawood ibn Kareem Nov 14 '13 at 01:57
  • I want to use isAlpha(or what ever it is for java) on a string, not a char. My compiler is telling me that isLetter is only for chars. Thanks for the link btw. – Bottlecaps Nov 14 '13 at 02:02
  • Well, the link I gave you will tell you one way of doing that. Not the only way, but one way. – Dawood ibn Kareem Nov 14 '13 at 02:04
  • Thanks! I was hoping there was a method in Java, but that would work too. – Bottlecaps Nov 14 '13 at 02:08

3 Answers3

8

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

Dariusz
  • 21,561
  • 9
  • 74
  • 114
5

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.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
UMESH0492
  • 1,701
  • 18
  • 31