Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex search and replace except for specific word

I’m trying to search and replace some strings in my code with RegEx as follows:

replacing self.word with self.indices[‘word’]

So for example, replace:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

self.example 

with

self.indices['example']

But it should work for all words, not just ‘example’.
So the RegEx needed for this probably doesn’t need the actual word in it.
It should actually just replace everything but the word itself.

What I tried is the following:

self.(.*?)

It works for searching all the strings that match ‘self.’ but when I want to change it I lose the word like ‘example’ so I can’t change it to self.indices[‘example’].

>Solution :

What you need to do is a substitution using capturing groups. Depending on the language used some of the syntax might be slightly different but in general you would want something like this:

self\.([^\s]+)

replace with:

self.indices['\1']

https://regex101.com/r/R3xFZB/1

We are using the parans to caputre what is after self. and in the replace putting that captured data into \1 which is the first (and in this case) only captured group. For some languages you might need $1 or \\1 for the substitution variable.

As with most regexes this can be done many different ways using look arounds, etc. but I think for somebody new this is easy to read, understand and maintain. The comment @wnull made has a more proper regex leveraging a look behind that should also do the trick 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading