Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx backreferences in IntelliJ

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.

like image 544
Dónal Avatar asked Sep 14 '09 14:09

Dónal


People also ask

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 does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


2 Answers

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.

like image 126
Steve K Avatar answered Oct 10 '22 17:10

Steve K


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

like image 29
Barett Avatar answered Oct 10 '22 18:10

Barett