在我的程序中,我将逐行读取Java文件,并且如果该行中有任何字符串文字,我将其替换为(例如)“ ABC”。
有正则表达式吗?
前任。如果传递给我的程序的Java文件是:
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文件应为:
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");
}
}
}
我很想知道正则表达式,它将帮助我检测所有字符串文字并将其替换为我选择的特定字符串。
编辑:
对我来说,真正的挑战是避免在字符串中使用那些引号字符。(如果有人将引号字符和转义字符放在字符串中)
考虑以下正则表达式:
String regex = "\"(?:\\\\\"|[^\"])*?\"";
它以引号开头,然后是零个或多个非引号字符或转义的引号字符。最后一个字符必须是引号。
如果将此正则表达式应用于Java代码,请记住,它也与注释中引号内的文本匹配。如果注释中的引号不平衡,则该字符串将不匹配字符串文字(然后将匹配完全相反的字符串)。
如果您有示例,则可以在String
名为example
以下变量的变量中发布该示例:
String wanted = example.replaceAll(regex, "\"ABC\"");
这是一个完整的例子:
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 = "" + "" + "";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句