6

I want to replace the below statement

ImageIcon("images/calender.gif");

with

ImageIcon(res.getResource("images/calender.gif"));

Can anyone suggest a regex to do this in eclipse.Instead of "calender.gif" any filename can come.

2 Answers 2

11

You can find this pattern (in regex mode):

ImageIcon\(("[^"]+")\)

and replace with:

ImageIcon(res.getResource($1))

The \( and \) in the pattern escapes the braces since they are to match literally. The unescaped braces (…) sets up capturing group 1 which matches the doublequoted string literal, which should not have escaped doublequotes (which I believe is illegal for filenames anyway).

The […] is a character class. Something like [aeiou] matches one of any of the lowercase vowels. [^…] is a negated character class. [^aeiou] matches one of anything but the lowercase vowels.

The + is one-or-more repetition, so [^"]+ matches non-empty sequence of everything except double quotes. We simply surround this pattern with " to match the double-quoted string literal.

So the pattern breaks down like this:

      literal(   literal)
         |          |
ImageIcon\(("[^"]+")\)
           \_______/
            group 1

In replacement strings, $1 substitutes what group 1 matched.

References

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain the above regex.
@Emil: note that this will not handle e.g. ImageIcon(getPath() + getFilename()) and funky things like that. A general Java expression is not regular, so a universal solution should use something other than regex.
0

Ctrl-F

Find: ImageIcon\("([^\"]*)"\);

Replace with: ImageIcon(res.getResource("\1"));

Check Regular Expressions checkbox.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.