23

I'm trying to find a way to split a String into an array of String(s), and I need to split it whenever a white spice is encountered, example

"hi i'm paul"

into"

"hi" "i'm" "paul"

How do you represent white spaces in split() method using RegularExpression?

sawa
  • 165,429
  • 45
  • 277
  • 381
JBoy
  • 5,398
  • 13
  • 61
  • 101
  • 11
    why do you even need regular expression for that? couldn't you just do `String[] myList = myString.split(" ");` – Mohamed Nuur May 22 '11 at 06:22
  • 1
    There is a tool called Visual REGEXP (http://laurent.riesterer.free.fr/regexp/) it can help you visualise the result of you regexp (perl regexp that is, but more or less all lang is using perl regexp so that is not a problem) – Johan May 22 '11 at 06:29
  • 1
    "i dont know that much yet about RegExp" - sounds like you need to remedy that, because asking someone else to write your regexes for you is not sustainable. – Stephen C May 22 '11 at 06:44

2 Answers2

54

You need a regular expression like "\\s+", which means: split whenever at least one whitespace is encountered. The full Java code is:

try {
    String[] splitArray = input.split("\\s+");
} catch (PatternSyntaxException ex) {
    // 
}
Staffan Nöteberg
  • 4,095
  • 1
  • 19
  • 17
7

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

kuriouscoder
  • 5,394
  • 7
  • 26
  • 40