Paul
Paul

Reputation: 6737

Grep and replace fuzzy pattern of string

I have a few files with python code and decorators like this:

@trace('api.module.function_name', info=None, custom_args=False)

The only difference between these decorators is the string 'api.module.function_name' - func name and module are different. And depending on the this param name sometimes this decorator is one-lined, some times it is two- or three-lined.

I want to replace these decorators with the other one - more simple, like "@my_new_decorator".

I thought about some regex but I have no idea if it's possible for such "fuzzy" search. I tried ^@trace([A-Za-z0-9]\, custom_args=False)$ But it doesn't work.

Is there a way to do it?

Upvotes: 0

Views: 172

Answers (2)

user6620326
user6620326

Reputation:

Use ^@trace\('api\.(.+)\.(.+)', info=None, custom_args=False\)$ with a multiline flag.

You may want to use re.sub :

>>> import re
>>> pattern = re.compile('^@trace\('api\.(.+)\.(.+)', info=None, custom_args=False\)$', re.M)
>>> re.sub(pattern, '@my_new_decorator('\1', '\2')', '@trace('api.module.function_name', info=None, custom_args=False)')
@my_new_decorator('module', 'function_name')

See this for the demo of the regex

As you can see \1 expand to the first group in the regex (.+)

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

Something like this should work:

(\n|^)\s*@trace\(\s*'[^']*',\s*info=None,\s*custom_args=False\s*\)\s*(\r|\n|$)

See the demo

Upvotes: 1

Related Questions