Skip to content

Can I use regex groups in the fix? #477

Answered by HerringtonDarkholme
Lodin asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks for trying out ast-grep!

Using regex group directly in fix is not possible. Because we can have multiple regex sub-rules in one YAML. It is not clear which group $1 refers to.

But ast-grep does have a (experimental) workaround.

transform is used to manipulate string in a matched variable. Refer to #436 (comment) for more explanation.

rule:
  pattern: $A
  regex: __PART_TO_REPLACE__(.*)
  kind: identifier
transform:
  CHANGED:
    replace:
      source: $A
      replace: __PART_TO_REPLACE__(.*)
      by: 'replaced$1'
fix:
  $CHANGED

https://ast-grep.github.io/playground.html#eyJtb2RlIjoiQ29uZmlnIiwibGFuZyI6ImphdmFzY3JpcHQiLCJxdWVyeSI6ImNvbnNvbGUubG9nKCRNQVRDSCkiLCJyZXdyaXRlIjoibG9nZ…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Lodin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants