Home > Mobile >  Regex: How to filter javascript code for nested functions
Regex: How to filter javascript code for nested functions

Time:10-18

I'm currently refactoring and I want to find nested subscriptions in my javascript Project. Im wondering how to do this with regex.

So the bad code could look like this:

something$.subscribe(() => {
  // ...
  another$.subscribe(() => {}) // should find .subscribe( here
  // ...
})

And I would like to find every .subscribe nested inside a .subscribe(() => { //nested }

CodePudding user response:

/\.subscribe\(.*\.subscribe\(/gms

works for me

CodePudding user response:

This problem relies on the number of curly braces {...} that need to be counted, which means you need a recursive regex. Such recursive regex is not possible in the vast majority of languages and therefore probably not your code editor. If the second .subscribe( is not nested in more curly braces, you could search for one curly brace, e.g

/\.subscribe\(.*?\{.*?\.subscribe\(/

If you would like to only match the last .subscribe:

/(?<=\.subscribe\(.*?\{.*?)\.subscribe\(/

Note that this will match

something$.subscribe(() => {
  // ...
  another$.subscribe(() => {})
  // ...
})

but not

something$.subscribe(() => {
  // ...
  if(...){
    another$.subscribe(() => {})
  }
  // ...
})

or

something$.subscribe(() => another$.subscribe(() => {}))
  • Related