Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace regex in Intellij, but keep some of the matched regex?

Tags:

I changed an array to a list, so I want to change all instances of myObject[index] to myObject.get(index) where index is different integers. I can find these instances by doing

`myObject\[.*\]`

However, I am not sure what I should put in the replace line - I don't know how to make it keep the index values.

like image 556
Andrew Avatar asked Nov 10 '16 22:11

Andrew


People also ask

Can you use regex in Find and Replace?

When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language. Press Ctrl+R to open the search and replace pane.

How do I find regex expressions in IntelliJ?

In IntelliJ IDEA 11 you can check your Regular Expressions while coding without leaving the IDE. Just invoke the 'Check RegExp' intention action on a regular expression and play! Tip: You can turn any string into a regular expression by injecting RegExp language. Try the 'Inject Language' intention action.

What is a capturing group regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .


1 Answers

Use the following regex replacement:

Find: myObject\[(.*?)\]
Replace: myObject.get($1)

If the index is an integer, you may replace (.*?) with (\d+).

The pair of unescaped parentheses creates a capturing group that we may reference from the replacement pattern using $ + Group ID. $1 will insert the index into the replacement result.

like image 116
Wiktor Stribiżew Avatar answered Sep 18 '22 12:09

Wiktor Stribiżew