Reputation: 16804
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?
Upvotes: 2
Views: 46530
Reputation: 359986
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
Upvotes: 9
Reputation: 19981
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.)
Upvotes: 2
Reputation: 22679
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. '\('
.
Upvotes: 8