Regex - Matching # hashtag/sharp character

Hello!

I’m having problems matching a # char with Regex.

I’m using something like this:

string notes = "[CDEFGAB]";
string accidentals = "(b|bb|#)?";
Regex regex = new Regex("\\b" + notes + accidentals);

The b and bb matches fine, but not the #

Do you have an example text where you try to find a match in? One potential issue you have is your match (b|bb|#)?. The issues is that the regex engine does match the first thing that matches. So a string like “Dbb” would match as “Db”. You should swap “b” and “bb”

string accidentals = "(bb|b|#)?";

I tried this code and I get 7 matches as expected:

        var m = regex.Match("C# F G Ab B Dbb A#");
        while (m.Success)
        {
            Debug.Log("match: " + m.Value);
            m = m.NextMatch();
        }