2
votes

I have the following code:

def commandType(self):
    import re
    print self.cmds[self.counter]
    if re.match("@",self.cmds[self.counter]):
        return Parser.A_COMMAND

    elif re.match('(',self.cmds[self.counter]):
        return Parser.L_COMMAND

    else:
        return Parser.C_COMMAND

and on this line: elif re.match('(',self.cmds[self.counter]):

I'm getting an error.

What am I doing wrong?

3
Maybe try replacing '(' with '\(' ..Worth a shot I guess.. - Bill VB
Some details regarding the error would have been useful. - Walter

3 Answers

9
votes

Parentheses have special meaning in regular expressions. You can escape the paren but you really do not need a regex at all for this problem:

def commandType(self):
    print self.cmds[self.counter]
    if '@' in self.cmds[self.counter]):
        return Parser.A_COMMAND

    elif '(' in self.cmds[self.counter]:
        return Parser.L_COMMAND

    else:
        return Parser.C_COMMAND
8
votes

The parenthesis '(' and ')' are used as grouping mechanism and scope operators in regexps. You have to escape them (and any other control symbols) via backslash, e.g. '\('.

1
votes

The language of regular expressions gives a special meaning to ( (it's used for starting a group). If you want to match a literal left-parenthesis, you need to escape it with a backslash: elif re.match(r'\(', ....

(Why r'...' rather than just '...'? Because in ordinary strings, backslashes are also used for escaping control characters and suchlike, and you need to write \\ to get a single backslash into the string. So you could instead write elif re.match('\\(', .... It's better to get into the habit of using r'...' strings for regular expressions -- it's less error-prone.)