Home > Blockchain >  Regex search and replace except for specific word
Regex search and replace except for specific word

Time:11-17

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:

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'].

CodePudding user response:

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 :)

  • Related