tags:

views:

89

answers:

2

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?

+5  A: 
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)
Tomalak
Both so quick of the mark! An this seems to work ok where it's a variabletag = '+test' (or tag='test')search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % r'\%s' % tag, re.I)Thank you both.
+3  A: 

Escape the plus:

r'\+test'

The plus has a special meaning in regexes (meaning "match the previous once or several times"). Since in your regex it appears after an open paren, there is no "previous" to match repeatedly.

balpha