Skip to content
Advertisement

how to prevent regex matching substring of words?

I have a regex in python and I want to prevent matching substrings. I want to add ‘@’ at the beginning some words with alphanumeric and _ character and 4 to 15 characters. But it matches substring of larger words. I have this method:

JavaScript

And the example is :

JavaScript

And the answer is :

JavaScript

As you can see, it puts ‘@’ at the beginning of ‘aabs’ and ‘kMMALke2l9’. That it is wrong. I tried to edit the code as bellow :

JavaScript

But the result will become like this :

JavaScript

As you can see It has wrong replacements. The correct result I expect is:

JavaScript

Could anyone help? Thanks

Advertisement

Answer

This is a pretty interesting question. If I understand correctly, the issue is that you want to divide the string by spaces, and then do the replacement only if the entire word matches, and not catch a substring.

I think the best way to do this is to first split by spaces, and then add assertions to your regex that catch only an entire string:

JavaScript

ie, we split, then replace only if the entire word matches, then rejoin.

By the way, your regex can be simplified to r'^(w{4,15})$':

JavaScript
Advertisement