Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array without deleting delimiter?

Tags:

I have a string like

 "asdf a  b c2 " 

And I want to split it into an array like this:

["asdf", " ", "a", " ", " ", "b", " ", "c2", " "] 

Using string.split(" ") removes the spaces, resulting in this:

["asdf", "a", "", "b", "c2"] 

I thought of inserting extra delimiters, e.g.

string.replace(/ /g, "| |").replace(/||/g, "|").split("|"); 

But this gives an unexpected result.

like image 393
gandalf3 Avatar asked Jul 01 '14 06:07

gandalf3


People also ask

How do you split a string without delimiter?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split without deleting?

To split a string without removing the delimiter: Use the str. split() method to split the string into a list. Use a list comprehension to iterate over the list. On each iteration, add the delimiter to the item.

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string with a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.


1 Answers

Instead of splitting, it might be easier to think of this as extracting strings comprising either the delimiter or consecutive characters that are not the delimiter:

'asdf a  b c2 '.match(/\S+|\s/g) // result: ["asdf", " ", "a", " ", " ", "b", " ", "c2", " "] 'asdf a  b. . c2% * '.match(/\S+|\s/g) // result: ["asdf", " ", "a", " ", " ", "b.", " ", ".", " ", "c2%", " ", "*", " "] 

A more Shakespearean definition of the matches would be:

'asdf a  b c2 '.match(/ |[^ ]+/g) 

To or (not to )+.

like image 99
Ja͢ck Avatar answered Oct 02 '22 13:10

Ja͢ck