2024-09-26 21:46:12 发布
网友
我想在python中使用正则表达式解析和弦名称。下面的代码只匹配G#m这样的和弦
chord_regex = "(?P<chord>[A-G])(?P<accidental>#|b)?(?P<additional>m?)"
我怎样才能将和弦与形状Gm#相匹配?上面的正则表达式可以被修改以匹配这些和弦类型吗?在
您应该使用{m,n}语法来指定一个组的m=0到{}匹配(其中所述组是意外的或附加的),如下所示:
{m,n}
m=0
>>> 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': '#'}
您应该使用}匹配(其中所述组是意外的或附加的),如下所示:
{m,n}
语法来指定一个组的m=0
到{相关问题 更多 >
编程相关推荐