Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse for tags with '+' in python

Tags:

python

regex

I'm getting a "nothing to repeat" error when I try to compile this:

search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I)

The problem is the '+' sign. How should I handle that?

like image 917
PhoebeB Avatar asked Jun 26 '09 11:06

PhoebeB


1 Answers

re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '\+test', re.I)

The "+" is the "repeat at least once" quantifier in regular expressions. It must follow something that is repeatable, or it must be escaped if you want to match a literal "+".

Better is this, if you want to build your regex dynamically.

re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % re.escape('+test'), re.I)
like image 163
Tomalak Avatar answered Sep 30 '22 17:09

Tomalak