简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM