Skip to content
Advertisement

Regex removes certain words from my string – Python

The below code is to lookup a dictionary and replace string with values corresponding to dict’s key.

JavaScript

Can someone help me understand why my code omits certain words?

It removes lh preceeded and followed with a . i.e., lh. and .lh. How to overcome this?

I get the output left hand l.h. -left hand- l.h plh phli lhp 1lh lh1

Advertisement

Answer

Because in the lookup dict you need to get capture group 3 instead of the whole match with m.group(0)

Note that w also matches d.

Now your pattern looks like:

JavaScript

But you can rewrite the structure of the pattern to just use group 1 m.group(1) for the dict key:

JavaScript

Regex demo

Advertisement