22

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?

3
  • 11
    why do you even need regular expression for that? couldn't you just do String[] myList = myString.split(" "); Commented May 22, 2011 at 6:22
  • 1
    There is a tool called Visual REGEXP (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) Commented May 22, 2011 at 6: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. Commented May 22, 2011 at 6:44

2 Answers 2

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) {
    // 
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Gabe: I don't think so. He wants anything, except whitespeces. For example he wants the apostrophe in "i'm" to be kept together with the i and the m.
Oops, I meant \s+! (as you have it now)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.