Matching a + in regular expression

It should be easy, but I managed to kick 2 people so far at work, and I have been on it for more than 3 hours, so it goes here.

I need to replace a + with aplus (along with several other cases) with the python re module. eg. "I passed the exam +". should be "I passed the aplus exam."

Just using \ ba + works great fine, but it doesn’t work in the case of + b, so I can’t use it, it must match the value + as a separate word. I tried \ ba + \ b, but this fails because I assume that the + character is a word boundary.

I also tried \ ba + \ W, which works, but is greedy and eats up space (or any other non-alpha char that will be there).

Any suggestions please?

+6
python regex
source share
3 answers

Turn this \W into a statement.

 \ba\+(?=\W) 

or better

 \ba\+(?!\w) 

since a negative statement also allows matching a+ at the end of the line.

+8
source share
 >>> re.sub(r'\ba\+\s', 'aplus ', 'I passed my a+ exam.') 'I passed my aplus exam.' >>> re.sub(r'\ba\+\s', 'aplus ', 'a+b') 'a+b' 
+1
source share

You need to get away from +, as it has special meaning in regexp (one or more a). search a\+ instead of a+

0
source share

All Articles