Regex for matching a music Chord

前端 未结 4 1720
野的像风
野的像风 2020-12-17 21:22

I am trying to write a function to parse the string representation of a musical chord.

Example: C major chord -> Cmaj (this is what I want to parse)

4条回答
  •  执念已碎
    2020-12-17 22:21

    Forgive the JavaScript, but on a purely REGEX point, this pattern seems to work. You didn't stipulate which numbers are allowed after which chord names but I've assumed 2 is allowed only after 'sus' and 7 only after 'min' and 'maj'.

    var chords = "C#maj7 C##maj Bbmaj7 Abmin2 Cbmin Dsus";
    var valid_chords = chords.match(/\b[CDEFGAB](?:#{1,2}|b{1,2})?(?:maj7?|min7?|sus2?)\b/g);
    

提交回复
热议问题