RegEx backreferences in IntelliJ

23,757

Solution 1

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

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

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

Share:
23,757
Dónal
Author by

Dónal

I earn a living by editing text files. I can be contacted at: [email protected] You can find out about all the different kinds of text files I've edited at: My StackOverflow Careers profile

Updated on June 23, 2020

Comments

  • Dónal
    Dónal over 2 years

    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.

  • Joe Tricarico over 8 years
    I found the same thing here; however, I ultimately had success using $1, without the backslash.
  • Ghedeon
    Ghedeon about 7 years
    Seems like "\" is not required: jetbrains.com/idea/help/…. Also, for me it works only if I explicitly surround my group with "()", otherwise I can't reference it later. Ex: search (foo) replace: $1bar
  • mindreader
    mindreader almost 6 years
    @Ghedeon: You should probably add your comment as an answer or to the existing answer. Your suggestion to put the expression in () is what worked for me.
  • worc
    worc about 5 years
    +1 the bit of information that solved my related problem: i'm replacing quote-plus wrappers around variables with dollar-curly wrappers, ie, '+ var +' to ${var} in some template strings and couldn't figure out why intellij wouldn't finish the replacement. turns out $ needs to be escaped in the replacement.