简体   繁体   中英

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] [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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM