用正则表达式分析和弦

2024-09-26 21:46:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 代码名称类型regexadditional形状chordgm
1条回答
网友
1楼 · 发布于 2024-09-26 21:46:12

您应该使用{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': '#'}

相关问题 更多 >

    热门问题