Giannis
Giannis

Reputation: 5526

regular expression to remove a space

I need a way to remove only the first space found in a string and then put the string in an array. For example

hello there. Hey.

I want that to be split like [hello][there. Hey]. I tried with

String [] s = str.split(" ")

by that will naturally remove all the spaces and create several strings. i just need 2. Can you please tell me how to do that ? Ether by regular expression or another way.

Upvotes: 1

Views: 799

Answers (2)

Miki
Miki

Reputation: 7188

String [] s = str.split (" ", 2); should do the trick, documentation here.

You may also want to consider using \s+ as the regex - it may split the string more intelligently.

Upvotes: 8

Denis de Bernardy
Denis de Bernardy

Reputation: 78423

Using a regular expression for this isn't necessarily your best option.

Find the first space using position() (whatever the java method is), and then use substring() from the beginning of the string to that position, and again from that position to the end of the string.

Upvotes: 0

Related Questions