I am trying to write a function to parse a string representation of a musical chord.
Example: C main chord - > Cmaj (this is what I want to parse)
Just to understand, a chord consists of three different parts:
- note (C, D, E, F, G, A)
- randomness for this note (#, ##, b, bb)
- chord name
For those who are versed in music, I do not consider slash chords (specifically).
The function below works. However, this still does not work for the following case:
- "C # maj" # matches and should
- "C # maj7" # matches and should
- "C # maj2" # matches and should not
I believe that if I could get some of the regular expression chords to be at the end of the regular expression, I did the trick. I tried using $ both before and after this line, but that didn't work.
Any idea? Thanks.
public static void regex(String chord) { String notes = "^[CDEFGAB]"; String accidentals = "[#|##|b|bb]"; String chords = "[maj7|maj|min7|min|sus2]"; String regex = notes + accidentals + chords; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(chord); System.out.println("regex is " + regex); if (matcher.find()) { int i = matcher.start(); int j = matcher.end(); System.out.println("i:" + i + " j:" + j); } else { System.out.println("no match!"); } }
regex music
nunos
source share