我試圖匹配包含和絃的行,但我需要確保每個匹配都被空白或首行所包含而不消耗字符,因爲我不希望它們返回給調用者。如何讓我的正則表達式匹配空白而不消耗它們?
E.g.
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
};
}
除了你的空白問題,你確定該模式是足夠的嗎?那麼和F13#11或C7b9或G11no3rd一樣的和絃呢? – nnnnnn
@nnnnnn你說得對。它不會匹配那些和絃。然而,我從來沒有遇到過這樣的事情(爵士樂和絃?),所以我必須調整模式,如果我需要他們。 – MdaG
那麼你很可能會看到像爵士樂表上的那些和絃,但真正和平9的和絃不是那麼晦澀。我曾經在搖滾樂中看過「E no 3rd」之類的東西,雖然有時會用圓括號表示「E(第三)」。 – nnnnnn