python - 我需要帮助编写用于检测和弦的正则表达式

标签 python regex

我正在将文本写入 cdr (chordpro) 转换器,但在检测表格上的和弦线时遇到问题:

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

这是我的 python 代码:

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)

我希望它返回一个列表 ["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

最佳答案

您应该通过将 (...) 更改为 (?:...) 来使您的组不捕获。

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.

关于python - 我需要帮助编写用于检测和弦的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031118/

相关文章:

python - xl.Workbook() (pyvot) 无法打开 Excel 工作簿

python - 接入开发服务器-Django

正则表达式在特定位置的模式中找不到子字符串

MySQL RegExp - 高级用法

python - 我可以将列表中的 2 个连续空字符串合并为 1 个空字符串,这样当我们有 4 个空字符串时,它应该合并并生成 2 个空字符串

regex - (?<= x)在正则表达式中是什么意思?

php - 使用 preg_replace_callback() 从 HTML 字符串中提取所有图像

python - 将指标函数应用于列表

python - 如何为 threading.Thread 和 multiprocessing.Pool 指定本地工作目录?

python - 无法使用 python3 安装 openCV 3.1.0。 CMAKE 未正确包含或链接 python