检查字符串istitle并相应地修改另一个字符串

时间:2017-01-11 14:07:36

标签: python regex

我有一个this vim插件的略微修改版本:

class SyntaxElement:
    def __init__(self, pattern, closingline):
        self.pattern = pattern
        self.closingline = closingline
    def match(self, line): 
        """ Return (indent, closingline) or (None, None)"""
        match = self.pattern.search(line)
        if match:
            indentpattern = re.compile(r'^\s*')
            variablepattern = re.compile(r'\$\{(?P<varname>[a-zA-Z0-9_]*)\}')
            indent = indentpattern.search(line).group(0)
            closingline = self.closingline
            # expand variables in closingline
            while True:
                variable_match = variablepattern.search(closingline)
                if variable_match:
                    try:
                        replacement = match.group(variable_match.group('varname'))
                    except:
                        print("Group %s is not defined in pattern" % variable_match.group('varname'))
                        replacement = variable_match.group('varname')
                    try:
                        closingline = closingline.replace(variable_match.group(0), replacement)
                    except TypeError:
                        if replacement is None:
                            replacement = ""
                        closingline = closingline.replace(variable_match.group(0), str(replacement))
                else:
                    break
        else:
            return (None, None)
        closingline = closingline.rstrip()
        return (indent, closingline)


def fortran_complete():

    syntax_elements = [
        SyntaxElement(re.compile(r'^\s*\s*((?P<struc>(program)))\s*((?P<name>([a-zA-Z0-9_]+)))', re.IGNORECASE),
                      'End ${struc} ${name}' )..]

我只添加了re.IGNORECASE

我的问题如下:

Fortran不区分大小写。因此,PROGRAMProgramprogram是等效的,这里是${struc}。但是,我也希望匹配End案例。所以,如果我写,Program,我想要&#34;结束&#34 ;;如果我写,PROGRAM,我想要&#34;结束&#34;。

因此,换句话说,我想检查Programistitleisupper还是lower,然后更改我的&#34;结束&#34;相应的字符串。

有可能吗?

1 个答案:

答案 0 :(得分:0)

正则表达式获得&#39; struc&#39;小组和比较。

if re.group('struc') == re.group('struc').title():
    end_stmt = 'End'
elif re.group('struc') == re.group('struc').lower():
    end_stmt = 'end'
elif re.group('struc') == re.group('struc').upper():
    end_stmt = 'END'
else:
    # etc.
    pass

syntax_elements = [
    SyntaxElement(..., end_stmt + '...')