我正在尝试匹配包含和弦的行,但我需要确保每个匹配都被空格包围或在不消耗字符的情况下首先出现,因为我不希望它们返回给调用者。
例如
Standard Tuning (Capo on fifth fret)
Time signature: 12/8
Tempo: 1.5 * Quarter note = 68 BPM
Intro: G Em7 G Em7
G Em7
I heard there was a secret chord
G Em7
That David played and it pleased the lord
C D G/B D
But you don't really care for music, do you?
G/B C D
Well it goes like this the fourth, the fifth
Em7 C
The minor fall and the major lift
D B7/D# Em
The baffled king composing hallelujah
Chorus:
G/A G/B C Em C G/B D/A G
Hal - le- lujah, hallelujah, hallelujah, hallelu-u-u-u-jah ....
几乎可以工作,除了它也匹配“68 BPM”中的“B”。现在如何确保和弦正确匹配?我不希望它与之前的 B 或 SUBSIDE 的 D 或 E 匹配?
这是我在每一行上匹配的算法:
function getChordMatches(line) {
var pattern = /[ABCDEFG](?:#|##|b|bb)?(?:min|m)?(?:maj|add|sus|aug|dim)?[0-9]*(?:\/[ABCDEFG](?:#|##|b|bb)?)?/g;
var chords = line.match(pattern);
var positions = [];
while ((match = pattern.exec(line)) != null) {
positions.push(match.index);
}
return {
"chords":chords,
"positions":positions
};
}
也就是说,我想要 ["A"、"Bm"、"C#"] 形式的数组,而不是 ["A"、"Bm"、"C#"]。
编辑
我使用接受的答案使其工作。我不得不进行一些调整以适应前导空格。感谢大家抽出宝贵的时间!
function getChordMatches(line) {
var pattern = /(?:^|\s)[A-G](?:##?|bb?)?(?:min|m)?(?:maj|add|sus|aug|dim)?[0-9]*(?:\/[A-G](?:##?|bb?)?)?(?!\S)/g;
var chords = line.match(pattern);
var chordLength = -1;
var positions = [];
while ((match = pattern.exec(line)) != null) {
positions.push(match.index);
}
for (var i = 0; chords && i < chords.length; i++) {
chordLength = chords[i].length;
chords[i] = chords[i].trim();
positions[i] -= chords[i].length - chordLength;
}
return {
"chords":chords,
"positions":positions
};
}