正则表达式替换Java文件中的所有字符串文字 [英] Regex to replace all string literals in a Java file

查看:260
本文介绍了正则表达式替换Java文件中的所有字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我将逐行读取一个java文件,如果该行中有任何字符串文字,我将用(例如)ABC替换它。

In my program I will be reading a java file line by line, and if there is any string literal in that line, i will replace it with (say) "ABC".

有没有正则表达式?

Ex。如果传递给我程序的Java文件是:

Ex. If the Java file passed to my program is:

public class TestClass {

    private static final boolean isNotThis = false;

    public static void main(String[] args) {
        String x = "This is a test String";
        dummyMethodCall();
        if(isNotThis){
            makeItThat();
            System.out.println("work is done");
        }
    }
}

然后输出java文件应该be:

Then the output java file should be:

public class TestClass {

    private static final boolean isNotThis = false;

    public static void main(String[] args) {
        String x = "ABC";
        dummyMethodCall();
        if(isNotThis){
            makeItThat();
            System.out.println("ABC");
        }
    }
}

我愿意知道正则表达式将帮助我检测所有字符串文字并用我选择的特定字符串替换它们。

I am willing to know the regex that will help me to detect all string literals and replace them with a particular string of my choice.

编辑:

对我来说真正的挑战是避免字符串中的那些引号字符。 (如果有人在字符串中放入带有转义字符的引号字符)

The real challenge for me is to avoid those quote-characters inside a string. (if somebody puts a quote character with an escape character inside the string)

推荐答案

请考虑以下正则表达式:

Consider the following regular expression:

String regex = "\"(?:\\\\\"|[^\"])*?\"";

它以引号开头,后跟零个或多个非引号字符或转义引号字符。最后一个字符必须是引号。

It starts with a quote, followed by zero or more non-quote characters or escaped quote characters. The last character has to be a quote.

如果将此正则表达式应用于java代码,请记住它还匹配注释中引号内的文本。如果你的评论中有不平衡的引号,它将不匹配字符串文字(然后它将完全相反)。

If you apply this regex to java code, remember that it also matches text inside quotes in comments. If you have unbalanced quotes in your comments it won't match string literals (it will then match the exact opposite).

如果你有一个你在字符串名为的变量示例以下内容可行:

If you had the example you posted in a String variable named example the following would work:

String wanted = example.replaceAll(regex, "\"ABC\"");

以下是一个完整的例子:

Here's a full example:

String literal = "String foo = \"bar\" + \"with\\\"escape\" + \"baz\";";
String regex = "\"(?:\\\\\"|[^\"])*?\"";
String replacement = "\"\"";
String wanted = literal.replaceAll(regex, replacement);
System.out.println(literal);
System.out.println(wanted);

打印

String foo = "bar" + "with\"escape" + "baz";
String foo = "" + "" + "";

这篇关于正则表达式替换Java文件中的所有字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆