Why does java give different result for guitar chords

DoWhileFor :

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

Marc G. Smith :

Your sharp expression is looking to match a space after it. The last chord in a line isn't matching that. You can either add a space to the line.

  Matcher m = p.matcher(line + " ");

or add an extra condition to your regular expression ([#b]$) and make sure the $ is set to match a new line vs the end of string using Pattern.MULTILINE.

   Pattern p = Pattern.compile("\\b[CDEFGAB](([#b]$)|([#b](?=\\s))|([#b]m7\\b)|([#b][m7]\\b)|(m7\\b)|([m7]\\b)|(\\b))", Pattern.MULTILINE);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140181&siteId=1