Home:ALL Converter>Get array of both matches and non-matches

Get array of both matches and non-matches

Ask Time:2017-02-18T05:11:20         Author:audoh

Json Formatter

What I want to do is split up a string into an array of multiple contiguous substrings, alternating between matches and non-matches of a given regular expression.

Like this:

[nonmatch, match, nonmatch, match...]

For example, with the right regex (the actual expression being not important here),

"I [went to the doctor] today to [eat some] food"

might become:

["I ", "[went to the doctor]", " today to ", "[eat some]", " food"]

I need to do this because I need to take out some parts of a string temporarily, do some stuff to the rest of the string, and then insert the previous parts back where they were to make the string whole again (by simply combining the entire array into a string).

All I can find from searching are people who want to either get rid of some of the string (e.g. the [] in the example above) or join some non-matches and matches together, like:

["I ", "[went to the doctor] today to ", "[eat some] food"]

Author:audoh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/42307451/get-array-of-both-matches-and-non-matches
yy