简体   繁体   中英

Parsing chords with regular expressions

I want to parse chord names using regular expressions in python. The following code matches only chords like G#m

chord_regex = "(?P<chord>[A-G])(?P<accidental>#|b)?(?P<additional>m?)"

How am I able to also match chords with the shape Gm#? Can the above regex be altered to also match these types of chords?

You should use the {m,n} syntax to specify m=0 to n=2 matches of a group (where said group is either the accidental or additional), like so:

>>> import re
>>> regex = "(?P<chord>[A-G])((?P<accidental>#|b)|(?P<additional>m)){0,2}"
>>> re.match(regex, "Gm").groupdict()
{'chord': 'G', 'additional': 'm', 'accidental': None}
>>> re.match(regex, "G").groupdict()
{'chord': 'G', 'additional': None, 'accidental': None}
>>> re.match(regex, "G#m").groupdict()
{'chord': 'G', 'additional': 'm', 'accidental': '#'}
>>> re.match(regex, "Gm#").groupdict()
{'chord': 'G', 'additional': 'm', 'accidental': '#'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM