0

I'm making a program about music chords. The first character has to be a single letter A through G. The second letter can contain an optional either "#", "b" or "" (nothing at all). And then I want a capital M followed by a 7.

For example, in one of my boolean statements I want "AM7" and "F#M7" to both evaluate to true, for both being a major chord in music theory.

Would this be something like:

/([A-G]{#b''}{M7})/$.test("GbM7");    //Should be true
/([A-G]{#b''}{M7})/$.test("GbbM7");    //Should be false
/([A-G]{#b''}{M7})/$.test("Gbm7");    //Should be false

I know the code above is wrong, but I am trying to illustrate my throught process of what i am going for. I feel like I am really close.

Thanks for any help!

4
  • What is it that you think the { } groups do? Commented Jul 12, 2017 at 20:20
  • Well the regex part for "either '#', 'b', or nothing" would be [b#]? Commented Jul 12, 2017 at 20:21
  • What is the $ after the regexp for? Commented Jul 12, 2017 at 20:22
  • I'm dumb. I thought the curly braces were used when there was a set set value that it could take on, as opposed to a range. I also thought that the money sign was used to end a regex. Sorry, regex is really hard for me to grasp for some reason. Commented Jul 12, 2017 at 20:28

2 Answers 2

3

Use ? to mark something optional.

/[A-G][#b]?M7/
Sign up to request clarification or add additional context in comments.

13 Comments

You could use a quantifier in that case: /([ABCDE][#b]?){1,5}M7/
@Team.Coco [A-G]{1,5} will match from 1 to 5 occurrences of that pattern.
For completeness, you might want to use beginning and end markers to rule out partial matches: /^([A-G][#b]?){1,5}M7$/. Otherwise, a string like 'dinosaurA#M7' would pass.
@buttonupbub It depends on whether this is for validation of a whole string or searching text for a match.
{1} is the default for any pattern, it matches 1 time unless there's a quantifier that modifies that.
|
2

I believe the expression you are looking for is

/[A-G][#b]?M7/

The ? marks the previous element ([#b]) as optional.

2 Comments

Thank you for your answer. I chose the above as best answer since they posted just a few seconds before you, but I appreciate your response!
Thanks for the feedback. Just joined Stack Overflow. Wow, these answers come out fast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.