Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

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

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

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

->

["two", "separate", "tokens", "this--is--just--one--token", "another"]

I naively tried str.split(/-(?!-)/) and it won't match the first occurrence of double delimiters, but it will match the second (as it is not followed by the delimiter):

["two", "separate", "tokens", "this-", "is-", "just-", "one-", "token", "another"]

Do I have a better alternative than looping through the string?

By the way, the next step should be replacing the two consecutive delimiters by just one, so it's kind of escaping the delimiter by repeating it... So the final result would be this:

["two", "separate", "tokens", "this-is-just-one-token", "another"]

If that can be achieved in just one step, that should be really awesome!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

str.match(/(?!-)(.*?[^-])(?=(?:-(?!-)|$))/g);

Check this fiddle.


Explanation:

Non-greedy pattern (?!-)(.*?[^-]) match a string that does not start and does not end with dash character and pattern (?=(?:-(?!-)|$)) requires such match to be followed by single dash character or by end of line. Modifier /g forces function match to find all occurrences, not just a single (first) one.


Edit (based on OP's comment):

str.match(/(?:[^-]|--)+/g);

Check this fiddle.

Explanation:

Pattern (?:[^-]|--) will match non-dash character or double-dash string. Sign + says that such matching from the previous pattern should be multiplied as many times as can. Modifier /g forces function match to find all occurrences, not just a single (first) one.

Note:

Pattern /(?:[^-]|--)+/g works in Javascript as well, but JSLint requires to escape - inside of square brackets, otherwise it comes with error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...