0

我有一个类似的字符串:

### init.sh [bash]
#!/c/Progra~2/Git/bin/sh.exe
git commit -am "[$1] $2"; git push

我一直在尝试匹配“init.sh”和“[bash]”,并且我有一个在RegExr上可以正常工作的正则表达式字符串,但在 Python 中不起作用。

正则表达式字符串是^(?<!\\)###\s*(.*?)(?:\[(.+?)\])?\s*$(?m),我正在通过

for match in _section_marker_re.finditer(code):
    filename, lang = match.groups()

我要对其进行正则表达式的字符串在哪里,_section_marker_re是哪里。re.compiled(regex)code

Python在这里可能会发生什么?

编辑:我正在使用 Python 2.7.3 并且 VERBOSE 没有打开。

编辑 2:使用此字符串的代码如下所示:

def highlight_multifile(code):
    """Multi-file highlighting."""
    result = []
    last = [0, None, 'text']

    def highlight_section(pos):
        start, filename, lang = last
        section_code = _escaped_marker.sub('', code[start:pos])
        if section_code:
            result.append(u'<div class="section">%s%s</div>' % (
                filename and u'<p class="filename">%s</p>'
                    % escape(filename + ' - ' + lang) or u'',
                highlight(section_code, lang)
            ))

    for match in _section_marker_re.finditer(code):
        start = match.start()
        highlight_section(start)
        filename, lang = match.groups()
        if lang is None:
            lang = get_language_for(filename)
        else:
            lang = lookup_language_alias(lang)
        last = [match.end(), filename, lang]

    highlight_section(len(code))

    return u'<div class="multi">%s</div>' % u'\n'.join(result)

我使用 _escaped_marker as re.compile(r'^\\(?=###)(?m)'),这标志着下一部分的开始。

4

1 回答 1

0

这个正则表达式似乎工作正常:

>>> regex = re.compile(r'^###\s*([^\[]+?)\s+(?:\[(.*?)\])?\s*', re.MULTILINE)
>>> text = """###init.sh [bash]
... #! c/Progra~2/Git/bin/sh.exe
... git commit -am "[$1] $2"; git push"""
>>> text2 = text.replace('[bash]', '')   #[bash] omitted
>>> regex.match(text).groups()
('init.sh', 'bash')
>>> regex.match(text2).groups()
('init.sh', None)

编辑:即使你的正则表达式也会给出相同的结果。可能您应该提供更多输入数据以了解它失败的原因。

>>> regex2 = re.compile(r'^(?<!\\)###\s*(.*?)(?:\[(.+?)\])?\s*$', re.MULTILINE)
>>> regex2.match(text).groups()
('init.sh ', 'bash')
>>> regex2.match(text2).groups()
('init.sh', None)
于 2013-01-23T06:50:28.697 回答