6

I'm trying to create a a regex that matches 2 or more spaces, or tabs, basically a combination of text.split(" ") and text.split("\t"). How do I create it?

My attempt: (but it doesn't work)

text.split(new RegExp("[  |\t]"))

Edit: This splits at spaces/tabs but I need to split at 2 spaces or more..

text.split("\\s+");
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

3 Answers3

10
\s{2,}

You can try in this way...! \s{2,} means 2 or more

I got this idea from this replace post Regex to replace multiple spaces with a single space

Demo: http://jsbin.com/akubed/1/edit

I agree with @Will comment - Add Tab space also

\s{2,}|\t
Naga Harish M
  • 2,779
  • 2
  • 31
  • 45
  • 1
    I was using this but it didn't worked for one tab. Had do switch to `\s{2,}|\t`. I guess it is correct, since i had only a single tab. – Will Jan 12 '15 at 18:47
1
String s="This      is      test";
    String [] as=s.split("\\t{2,}");
    for(int i=0;i<as.length;i++)
    System.out.println(as[i]);

This works for me.

Shivam Bharadwaj
  • 1,864
  • 21
  • 23
0

I would suggest my function below. It separates every word, independent from any amount of spaces/tabs.

const filterWords = (text) => {
    const wordList = text.split(" ");
    let trimmedWordList = [];

    for (let index = 0; index < wordList.length; index++) {
        trimmedWordList.push(wordList[index].trim());
    }

    return trimmedWordList.filter(function (e) {
        return e !== "";
    });
}

console.log(filterWords("    This       is a demo      text"));
Arno.bln
  • 1
  • 1