Split at single separator occurrence

javascript

Solution

>>> "A_B_C_D".match(/(?:[^_]|_{2,})+/g)
["A", "B", "C", "D"]

>>> "A_B___C_D".match(/(?:[^_]|_{2,})+/g)
["A", "B___C", "D"]

Instead of finding the separators, we find the components themselves. Notice that the strings must be either non-`_`'s (because the separator is `_`), or more than one `_`s. So the regex to match them is simply like this.

Note that this regex ignores the empty strings if the input starts or ends with `_` (e.g. `"_a_"` will just return `["a"]`.)

Problem

I have strings like ``` A_B_C_D A_B___C_D ``` where the `___`could be anywhere in the string. What is the easiest way to split them at any single `_` but not at `___`?

Original source