Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a+ in a regex

Tags:

python

regex

This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes.

I need to replace a+ with aplus (along with a few other cases) with the Python re module. eg. "I passed my a+ exam." needs to become "I passed my aplus exam."

Just using \ba+ works fine most of the time, but fails in the case of a+b, so I can't use it, it needs to match a+ as a distinct word. I've tried \ba+\b but that fails because I assume the + is a word boundary.

I've also tried \ba+\W which does work, but is greedy and eats up the space (or any other non-alpha char that would be there).

Any suggestions please?

like image 984
dochead Avatar asked Jun 08 '10 13:06

dochead


1 Answers

Turn that \W into an assertion.

\ba\+(?=\W)

or, better,

\ba\+(?!\w)

since the negative assertion allows matching the a+ at end of string too.

like image 178
kennytm Avatar answered Sep 28 '22 08:09

kennytm