In eclipse, is it possible to use the matched search string as part of the replace string when performing a regular expression search and replace?
Basically, I want
Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2
...replaces ...
from checks import checklist(_list):
...with...
from checks import checklist
Blocks in regex are delineated by parenthesis (which are not preceded by a "\")
(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)
(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)
(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"
Then in the replace, just put the $1$2 to replace all three blocks with just the first two.
Yes, "( )" captures a group. you can use it again with $i where i is the i'th capture group.
So:
search:
(\w+\.someMethod\(\))
replace:
((TypeName)$1)
Hint: CTRL + Space in the textboxes gives you all kinds of suggestions for regular expression writing.
For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.
I want to rename
/download.mp4^lecture_id=271
to
/271.mp4
And there can be multiple of these.
Here is how it should be done.
Then hit find/replace button
NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is
search: (\w+\.someMethod\(\))
replace: ((TypeName)$1)
Here:
In search:
First and last '(' ')' depicts a group in regex
'\w' depicts words (alphanumeric+underscore)
'+' depicts one or more(ie one or more of alphanumeric+underscore)
'.' is a special character which depicts any character( ie .+ means one or more of any character). Because this is a special character to depict a '.' we should give an escape character with it, ie '.'
'someMethod' is given as it is to be searched.
The two parenthesis '(',')' are given along with escape character because they are special character which are used to depict a group (we will discuss about group in next point)
In replace:
It is given '((TypeName)$1)', here $1 depicts the group. That is all the characters that are enclosed within the first and last parenthesis '(' ,')' in the search field
Also make sure you have checked the 'Regular expression' option in find an replace box
More information about RegEx can be found in http://regexr.com/.
At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be
replace: ((TypeName)$0)