Reputation: 2087
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
Reputation: 174696
You may try this regex which uses word boundaries.
string.split("\\b\\s\\b");
Upvotes: 1
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
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:
(?<!a)b
matches "b" that's not preceded by an "a"b(?!a)
matches "b" that's not followed by an "a"Further reading:
Upvotes: 4