RegEx backreferences in IntelliJ

JavaRegexIntellij Idea

Java Problem Overview


I want to use IntelliJ's find-and-replace feature to perform the following transformation:

// Replace this
model.put('foo', 'bar')
// With this
model['foo'] = bar

I've tried the following:

Text to find: model.put\((.*),(.*)\) Replace with: model\[\\1\] = \\2

But Intellij doesn't seem to recognise \\1 and \\2 as backreferences. I've also tried a single slash, but that doesn't work either.

Java Solutions


Solution 1 - Java

IntelliJ uses $1 for replacement backreferences.

From IntelliJ's help:

> For more information on regular expressions and their syntax, refer to documentation for java.util.regex Back references should have $n, rather than \n format.

Solution 2 - Java

In short, you must use $1 to $n for replacement backreferences. \1 syntax is only for backreferences within the search.

In IntelliJ 2016, the in-app documentation is misleading. Here is a better quote from the full docs:

> If you need to refer the matched substring somewhere outside the current regular expression (for example, in another regular expression as a replacement string), you can retrieve it using the dollar sign ($num, where num = 1..n).

Source: 2016.1 regular expression syntax, Tips & Tricks

Solution 3 - Java

The in-product contextual help for regex in Idea 9.0 (and perhaps other versions) appears to be incorrect. It states this:

Back references
\n
Whatever the nth capturing group matched

But apparently, as mentioned in previous answers and is my experience, it's really $n for back references, rather than \n

You get to this contextual help by clicking the '[Help]' link next to the "Regular expression" radio option on the the "Replace Text" dialog box

Solution 4 - Java

IntelliJ IDEA /  Reference /  Regular Expression Syntax Reference


Matches subexpression and remembers the match. If you need to use the matched substring within the same regular expression, you can retrieve it using the backreference (\num, where num = 1..n). If you need to refer the matched substring somewhere outside the current regular expression (for example, in another regular expression in the Replacement field), you can retrieve it using the dollar sign ($num, where num = 1..n). If you need to include the parentheses characters into the subexpression, use "(" or ")".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDónalView Question on Stackoverflow
Solution 1 - JavaSteve KView Answer on Stackoverflow
Solution 2 - JavaBarettView Answer on Stackoverflow
Solution 3 - JavaGlenView Answer on Stackoverflow
Solution 4 - JavaCong De PengView Answer on Stackoverflow