0

Suppose you had a Java file which contained lots of single letter variable names like a,x,f etc, and you wanted to change them to something more meaningful. You could try replacing every occurrence of ‘f’ with ‘filename’, but that would mess up all of the places where ‘f’ occurs inside a word (for example in the keyword if ). How would you go about correcting this problem using regular expression search and replace?

I need to write this in Emacs, using word boundaries. Since I am new, does using the Matcher Class apply?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
user2282137
  • 39
  • 10

3 Answers3

0

If you must do this using native emacs: Word boundaries are a reasonable search boundary. The Matcher class is a Java construct. If you were writing code to do the search and replace. Since you are doing this completely in emacs, it wouldn't apply.

There is a caveat that these variables can't be used from multiple source files or you will mess things up.

I wouldn't do this with raw emacs though. I'd use an IDE refactoring tool. Emacs even has a Java Refactoring that you can install. Using a refactoring tool, the tool understands the syntax and will be more specific than a regular expression.

Jeanne Boyarsky
  • 12,156
  • 2
  • 49
  • 59
0

Here's an answer based on this question:

  1. Before doing this kind of stuff with any tool, version-control everything. I recommend git.
  2. M-x find-name-dired.
  3. Enter the path to your project root, e.g. ~/Dropbox/source/java/.
  4. Enter the java file wildcard: *.java. You'll end up in a dired buffer with all the java files in your project root.
  5. t - this will mark all the files in dired. It means they'll be the target of the next operation.
  6. Q - this calls dired-do-query-replace-regexp. Now you're prompted for what you want replaced - enter e.g. \bf\b. Next, enter the replacement e.g. filename.
  7. Now Emacs will walk you though all occurrences of \bm\b in all your java files. You have to type each time either SPC to accept or n to skip the current instance. You can see all the options while replacing by typing ?.
  8. Finally, C-x s.
Community
  • 1
  • 1
abo-abo
  • 20,038
  • 3
  • 50
  • 71
0

\bj\b where the letter i is supposed to be found. So anything bound between the b's is the character to be found.

user2282137
  • 39
  • 10