[英]Search and replace strings in Java source files using Emacs and regular expressions
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. 假设您有一个Java文件,其中包含许多单字母变量名称,例如a,x,f等,并且您想将其更改为更有意义的名称。 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 ).
您可以尝试将所有出现的'f'替换为'filename',但这会弄乱单词中所有出现'f'的位置(例如,关键字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. 我需要使用单词边界在Emacs中编写此代码。 Since I am new, does using the Matcher Class apply?
由于我是新手,因此使用Matcher类是否适用?
If you must do this using native emacs: Word boundaries are a reasonable search boundary. 如果必须使用本机emacs执行此操作:单词边界是一个合理的搜索边界。 The Matcher class is a Java construct.
Matcher类是Java构造。 If you were writing code to do the search and replace.
如果您正在编写代码来进行搜索和替换。 Since you are doing this completely in emacs, it wouldn't apply.
由于您是完全在emacs中完成此操作,因此它不适用。
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. 我不会用原始emacs做到这一点。 I'd use an IDE refactoring tool.
我将使用IDE重构工具。 Emacs even has a Java Refactoring that you can install.
Emacs甚至可以安装Java重构 。 Using a refactoring tool, the tool understands the syntax and will be more specific than a regular expression.
使用重构工具,该工具可以理解语法,并且比正则表达式更加具体。
Here's an answer based on this question : 这是基于这个问题的答案:
find-name-dired
. find-name-dired
。 ~/Dropbox/source/java/
. ~/Dropbox/source/java/
。 *.java
. *.java
。 You'll end up in a dired
buffer with all the java files in your project root. dired
缓冲区中。 dired-do-query-replace-regexp
. dired-do-query-replace-regexp
。 Now you're prompted for what you want replaced - enter eg \\bf\\b
. \\bf\\b
。 Next, enter the replacement eg filename
. filename
。 \\bm\\b
in all your java files. \\bm\\b
出现。 You have to type each time either SPC to accept or n to skip the current instance. \\bj\\b where the letter i is supposed to be found. \\ bj \\ b应该在找到字母i的位置。 So anything bound between the b's is the character to be found.
因此,b之间的任何绑定都是要找到的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.