我想在 python 中使用正则表达式解析和弦名称。以下代码仅匹配 G#m 等和弦
chord_regex = "(?P<chord>[A-G])(?P<accidental>#|b)?(?P<additional>m?)"
我怎样才能将和弦与形状 Gm# 相匹配?可以更改上述正则表达式以匹配这些类型的和弦吗?
最佳答案
您应该使用 {m,n}
语法来指定组的 m=0
到 n=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': '#'}
关于python - 用正则表达式解析和弦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326204/