Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split at single separator occurrence

Tags:

javascript

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 ___?

like image 296
Marcus Bitzl Avatar asked Apr 30 '12 08:04

Marcus Bitzl


People also ask

Can Split have multiple separators?

The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

How do you split a string in a second occurrence?

a. split("-", 2) will split the string upto the second occurrence of - . a. split("-", 2)[:2] will give the first 2 elements in the list.

What is the default separator in split ()?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


1 Answers

>>> "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"].)

like image 50
kennytm Avatar answered Oct 12 '22 23:10

kennytm