Knows Not Much
Knows Not Much

Reputation: 31546

Search and replace text using Regex in IntelliJ

I am using the latest version of the IntelliJ Idea 2017.1

In my project I have many calls to this function

foo.bar(x)

I want to search and replace this to x.toFoo

The problem is that X can be anything. it can be any variable, it can be a long function call. So we don't really know the pattern for x.

I tried this regex

foo.bar(\S+) but this doesn't work as it selects many other things.

I also tried foo.bar(\()(.*)(\)) this seems to select the right thing. but at the time of replacing. how do I remember to capture whatever was there in .*?

Example

foo.bar(myobj.copy(myid = hisId))

this should become

myobj.copy(myid = hisId).toFoo

another example can be

foo.bar(List(1, 2, 3))

List(1, 2, 3).toFoo

Upvotes: 0

Views: 378

Answers (1)

vallentin
vallentin

Reputation: 26157

Since your string can have nested parenthesis, I would have suggested using recursion:

foo\.bar(\(([^()]|(?1))*\))

Live preview

However IntelliJ doesn't support that (actually haven't seen any IDE supporting recursion).

So instead you can use:

foo\.bar[^\(]*(\(.*\))[^\)]*?

Live preview

Which given this:

foo.bar()
foo.bar(1, 2, 3)
foo.bar(1, (2 + (3 + 4)), 5)

You didn't give any example, so I just made some containing nested parenthesis.

Results in:

().toFoo
(1, 2, 3).toFoo
(1, (2 + (3 + 4)), 5).toFoo

Upvotes: 1

Related Questions