Is there a way to regex from digit to digit?
I have this tracklist:
01. Intro 02. Waage 03. Hyänen (feat. Samra) 04. Ich will es bar (feat. Haftbefehl) 05. Am Boden bleiben (feat. Casper & Montez) 06. Panzerglas (feat. Face) 07. Sobald Du gehst 08. 90’s (feat. Olson) 09. Erzähl‘ mir nix (feat. Nio) 10. Dope & 40s 11. Lila (feat. Bosca) 12. Wo ich wohn‘ 13. Bahnen 14. 200K
which I tried to split with /\d\d([^\d]*)/g
into objects. But I got as a result:
0: ""
1: ". Intro "
2: ""
3: ". Waage "
4: ""
5: ". Hyänen (feat. Samra) "
6: ""
7: ". Ich will es bar (feat. Haftbefehl) "
8: ""
9: ". Am Boden bleiben (feat. Casper & Montez) "
10: ""
11: ". Panzerglas (feat. Face) "
12: ""
13: ". Sobald Du gehst "
14: ""
15: ". "
16: ""
17: "’s (feat. Olson) "
18: ""
19: ". Erzähl‘ mir nix (feat. Nio) "
20: ""
21: ". Dope & "
22: ""
23: "s "
24: ""
25: ". Lila (feat. Bosca) "
26: ""
27: ". Wo ich wohn‘ "
28: ""
29: ". Bahnen "
30: ""
31: ". "
32: ""
33: ""
34: "0K"
How do I include the numbers 01
, 02
, 03
... and what are the possibilites for cases like track 14 where the title track is 200k
?
CodePudding user response:
You can use
text.split(/\s (?=\d \.\s)/)
See the regex demo. Details:
\s
- one or more whitespaces(?=\d \.\s)
- a positive lookahead that requires one or more digits,.
and a whitespace to occur immediately to the right of the current location.
See the JavaScript demo:
const text = "01. Intro 02. Waage 03. Hyänen (feat. Samra) 04. Ich will es bar (feat. Haftbefehl) 05. Am Boden bleiben (feat. Casper & Montez) 06. Panzerglas (feat. Face) 07. Sobald Du gehst 08. 90’s (feat. Olson) 09. Erzähl‘ mir nix (feat. Nio) 10. Dope & 40s 11. Lila (feat. Bosca) 12. Wo ich wohn‘ 13. Bahnen 14. 200K";
text.split(/\s (?=\d \.\s)/).forEach( x =>
console.log(x))
If you need to make sure the bullet numbers come in incrementally, you need to adjust the code to
const text = "01. Intro containing 26. chars 02. Waage 03. Hyänen (feat. Samra) 04. Ich will es bar (feat. Haftbefehl) 05. Am Boden bleiben (feat. Casper & Montez) 06. Panzerglas (feat. Face) 07. Sobald Du gehst 08. 90’s (feat. Olson) 09. Erzähl‘ mir nix (feat. Nio) 10. Dope & 40s 11. Lila (feat. Bosca) 12. Wo ich wohn‘ 13. Bahnen 14. 200K";
var chunks = text.split(/\s (?=\d \.\s)/)
chunks = chunks.reduce(
function(acc, currentValue, index) {
if (index>0) {
const num = Number(currentValue.match(/^\d /)[0])
if (num - num_prev === 1) {
acc.push(currentValue); num_prev = num;
} else {
acc[acc.length-1] = ` ${currentValue}`;
}
return acc;
} else {
acc = [currentValue]; num_prev = 1;
return acc;
}
}, [])
chunks.forEach( x =>
console.log(x))