2013-03-10 57 views
1

我想在python中使用正则表达式分析和弦名称。下面的代码只匹配G#m用正则表达式分析和弦

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

我怎样才能将和弦与形状Gm#相匹配?上述正则表达式是否可以修改为匹配这些类型的和弦?

+0

看一看在http://计算器。 com/questions/11229080/regex-for-matching-a-music-chord – 2013-03-10 19:11:56

+0

http://stackoverflow.com/questions/11229597/music-chord-regex和http://regexadvice.com/forums/thread/20327。 aspx – 2013-03-10 19:12:30

+0

谢谢,但没有一个链接回答我的问题。我有一个非常具体的问题,即如何更改上述正则表达式来涵盖这两种情况。我不想寻找正则表达式来解析任意和弦,例如Cmaj7或G#add9。 – anopheles 2013-03-10 19:25:31

回答

2

您应该使用{m,n}语法指定m=0n=2一组(其中该基团的任何意外或附加)的比赛中,像这样:

>>> 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': '#'}