ast-grep icon indicating copy to clipboard operation
ast-grep copied to clipboard

[feature] support replacing only the first instance of a regex

Open emosenkis opened this issue 1 year ago • 3 comments

⭐ Suggestion

💻 Use Cases

Add an import to a file that uses the imported code (especially useful as a follow-up to a fix that starts using a module that may not be imported in the impacted file).

This is currently possible using (?ms)(.*)(stuff-i-actually-want-to-replace) with: ${1}actual-replacement but it's a nuisance especially if you wanted to use . with its usual meaning in stuff-i-actually-want-to-replace since it now matches newlines also

emosenkis avatar Jul 07 '24 15:07 emosenkis

Sorry I don't quite understand the issue here.

Can you give a more concrete example?

HerringtonDarkholme avatar Jul 07 '24 22:07 HerringtonDarkholme

The request is the be able to choose whether the replace transformer uses replace_one or replace_all. My use case is that I want to add an import import foo to a Python file. It needs to be added next to whatever other imports are at the top of the file, after any initial comments or docstring. I'm using a pattern that matches the entire module when that module contains foo.bar() and using a replace transformer to add import foo before import .*. It would be straightforward to do this if I could tell it to only replace one instance (I want toimport foo once per file, not once for every existing import) but since the replace transformer replaces all matches, I have to work around that by including (?ms)(.*) at the beginning of the regex, forcing it to only match the first instance from the start of the file (but then I have to be careful with . in the rest of the regex since the s flag makes it match newlines.

emosenkis avatar Jul 08 '24 04:07 emosenkis

I still think this is a good capability to provide since every regex library I'm aware of allows you to replace all non-overlapping matches or only the first match (some let you set a maximum number of matches to replace).

I did find a cleaner way to handle adding imports though without resorting to regex.

emosenkis avatar Jul 08 '24 12:07 emosenkis