kechap
kechap

Reputation: 2087

Splitting a string using regex at exactly one space

I am trying to split a string using spaces but only if there is one space.

For example I have the following.

String s = "THIS IS A  TEST";

I want to take the result "THIS", "IS", "A TEST". How to form the regex to do the job?

Upvotes: 1

Views: 333

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174696

You may try this regex which uses word boundaries.

string.split("\\b\\s\\b");

Upvotes: 1

Rachit Ahuja
Rachit Ahuja

Reputation: 369

Since the argument to split() is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").

String[] array = s.split(" +");

You can also add and argument to limit the number of slips you want to split the string into.

String[] array = s.split(" +", N );

Where N is the number of splits you want to divide the string into.

Upvotes: 1

Maroun
Maroun

Reputation: 95958

Use lookarounds:

(?<!\s)(\s)(?!\s)

This regex matches space that's not followed and not preceded by a space.

In Java, it'll look:

"THIS IS A  TEST".split("(?<!\\s)(\\s)(?!\\s)");

Explanation:

  • The regex (?<!a)b matches "b" that's not preceded by an "a"
  • The regex b(?!a) matches "b" that's not followed by an "a"

Further reading:

Upvotes: 4

Related Questions