Split string with a single occurence (not twice) of a delimiter in Javascript

前端 未结 6 1430
星月不相逢
星月不相逢 2020-12-18 05:04

This is better explained with an example. I want to achieve an split like this:

two-separate-tokens-this--is--just--one--token-another

->

6条回答
  •  Happy的楠姐
    2020-12-18 05:23

    @Ωmega has the right idea in using match instead of split, but his regex is more complicated than it needs to be. Try this one:

    s.match(/[^-]+(?:--[^-]+)*/g);
    

    It reads exactly the way you expect it to work: Consume one or more non-hyphens, and if you encounter a double hyphen, consume that and go on consuming non-hyphens. Repeat as necessary.


    EDIT: Apparently the source string may contain runs of two or more consecutive hyphens, which should not be treated as delimiters. That can be handled by adding a + to the second hyphen:

    s.match(/[^-]+(?:--+[^-]+)*/g);
    

    You can also use a {min,max} quantifier:

    s.match(/[^-]+(?:-{2,}[^-]+)*/g);
    

提交回复
热议问题