Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java give different result for guitar chords

Tags:

java

regex

First, I try to extract all guitar chords from a simple text file using a regular expression. To me, it is working on https://regexr.com/ but it isn't working properly in java.

In this (simplified) task, a chord

  • should start with an upper case letter (CDEFGAB) (it is required always)
  • it can be followed by # or b (just one of them)
  • it also could be followed by m, 7, or m7 (just one of them)
  • if there is # or b then it precedes m, 7, or m7
  • the chord shouldn't be bounded by a word character (i.e. "\nA#7 " would be a good example)

I'm using Netbeans 8.2 IDE. I tried the following code snippet:

try (BufferedReader br = new BufferedReader(new FileReader(textFile))) {
    while ((line = br.readLine()) != null) {     
        Pattern p = Pattern.compile("\\b[CDEFGAB](([#b](?=\\s))|([#b]m7\\b)|([#b][m7]\\b)|(m7\\b)|([m7]\\b)|(\\b))");
        Matcher m = p.matcher(line);

        while (m.find()) {
            chords.add(m.group());
        }
    }
}

I get most chords but not the ones end with # and stand at the end of a line. I.e. I get only "F" (instead of "F#") here:

"C# F#\n"

It could be a good text for it: https://tabs.ultimate-guitar.com/tab/george_benson/nothings_gonna_change_my_love_for_you_chords_1080047

like image 427
DoWhileFor Avatar asked Dec 21 '25 04:12

DoWhileFor


1 Answers

You could do this with a much simpler regex:

Pattern.compile("\\b[A-G][b#]?m?7?(?!\\w)")

This should do exactly what you need. You can even expand it (Guitars have major and diminished 7th chords too, right?)

Pattern.compile("\\b[A-G][b#]?(7|m7?|M7|dim7?)?(?!\\w)")
like image 174
Leo Aso Avatar answered Dec 23 '25 23:12

Leo Aso