How to parse tags with '+' in python

I get a "do not repeat anything" 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 do I handle this?

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

A β€œ+” is β€œrepeat at least once” in regular expressions. It must follow something that is repeatable, or it must be escaped if you want to combine the literal "+".

This is better if you want to dynamically build your regular expression.

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

Escape Plus:

 r'\+test' 

Plus has special meaning in regular expressions (the value "matches the previous one or more times"). Since it appears in your regex after an open pair, there is no β€œprevious” to match again.

+5
source

Source: https://habr.com/ru/post/1286806/


All Articles