Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbalanced parenthesis python

Tags:

python

regex

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?

like image 490
Itzik984 Avatar asked Aug 31 '26 21:08

Itzik984


2 Answers

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
like image 63
Matt Ball Avatar answered Sep 02 '26 11:09

Matt Ball


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. '\('.

like image 43
Zaur Nasibov Avatar answered Sep 02 '26 13:09

Zaur Nasibov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!