我需要帮助编写一个检测和弦的正则表达式

2024-06-26 14:49:40 发布

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

我正在编写一个文本到cdr(chordpro)转换器,但在表单上检测和弦线时遇到问题:

               Cmaj7    F#m           C7    
Xxx xxxxxx xxx xxxxx xx x xxxxxxxxxxx xxx 

这是我的python代码:

^{pr2}$

我希望它返回一个列表[“Cmaj7”,“F#m”,“C7”]。上面的代码不起作用,我一直在努力编写文档,但我什么也做不到。在

为什么不把类和组链接在一起呢?在

编辑

谢谢,我最后给出了下面的内容,它涵盖了我的大部分需求(例如,它不符合E#m11)。在

def getChordMatches(line):
    import re

    notes = "[ABCDEFG]";
    accidentals = "(?:#|##|b|bb)?";
    chords = "(?:maj|min|m|sus|aug|dim)?"
    additions = "[0-9]?"
    chordFormPattern = notes + accidentals + chords + additions
    fullPattern = chordFormPattern + "(?:/%s)?\s" % (notes + accidentals)
    matches = [x.replace(' ', '').replace('\n', '') for x in re.findall(fullPattern, line)]
    positions = [x.start() for x in re.finditer(fullPattern, line)]

    return matches, positions

Tags: 代码reforlinereplacexxxnotesmatches
3条回答

您应该通过将(...)更改为(?:...),使您的组成为非捕获组。在

accidentals = "(?:#|##|b|bb)?";
chords = "(?:maj|min|m|sus|aug|dim)?";

在线查看:ideone


当您捕获组时它不起作用的原因是它只返回那些组而不是整个匹配。根据文件:

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

您需要使组不被捕获:

def getChordMatches(line):
    import re
    notes = "[CDEFGAB]";
    accidentals = "(?:#|##|b|bb)?";
    chords = "(?:maj|min|m|sus|aug|dim)?";
    additions = "[0-9]?"
    return re.findall(notes + accidentals + chords + additions, line)

结果:

^{pr2}$

有一种用于编写详细正则表达式的特定语法

regex = re.compile(
    r"""[CDEFGAB]                 # Notes
        (?:#|##|b|bb)?            # Accidentals
        (?:maj|min|m|sus|aug|dim) # Chords
        [0-9]?                    # Additions
     """, re.VERBOSE
)
result_list = regex.findall(line)

可以说,这比把绳子连在一起要清楚一点

相关问题 更多 >