【问题标题】:Parsing chords with regular expressions用正则表达式解析和弦
【发布时间】:2013-03-10 18:58:05
【问题描述】:

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

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

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

【问题讨论】:

标签: python parsing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多