在字面上,我指的是像这样的所有常量
这里10是整数字面量,10.5f是浮点字面量,Hello是字符串字面量,但是在尝试了一些东西之后,我在代码的某些部分还是成功了。
int a = 10;
float b = 10.5f;
String all = "Hello";
String s = "my source program that i am reading from file";
String lines[] = s.split("\n"); //Break my program into lines
for(int i=0;i<lines.length;i++) {
if(lines[i].contains("="))
System.err.println(lines[i].substring(lines[i].indexOf("=")+1),lines[i].indexOf(";"));
}
但它也为我提供了如下任务的输出:
Myapp a=new Myapp();
但是,我只需要查找文字
发布于 2015-03-14 22:46:25
虽然有更好的方法来解决这个问题,但在现有代码中的一个快速修复方法是做一个小调整:
String s = "my source program that i am reading from file";
String lines[] = s.split("\n"); // Break my program into lines
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains("=")) {
String literal = lines[i].substring((lines[i].indexOf("=") + 1), lines[i].indexOf(";"));
if (!literal.contains("new"))
System.err.println(literal);
}
}
发布于 2015-03-15 00:19:31
如果你真的想找到所有的文字,连接一个java解析器或者使用"javap“工具来查看生成的类文件。在包含以下行的代码中运行它:
int a = 20;
long b = 10L;
float c = 1.10E12f;
并且使用"grep“只选择那些描述长、浮点数和字符串的行,返回
javap -c Main.class | grep -E "const|push|//" | grep -vE "Field|Method|class"
0: bipush 20
2: ldc2_w #2 // long 10l
6: ldc #4 // float 1.1E12f
这将查找所有的文字。即使是字符串中的那些,隐式的(i++
)或以某种方式引用的。请注意,int
文字只能通过bipush
和iconst_*
指令定位,因为javap反编译器不会为它们生成注释。有关字节码和常量here的更多信息
如果您只对形式为<atomicType> <identifier> = <literal>;
的简单行感兴趣-那么使用正则表达式搜索它们:
String pattern =
"\\s*\\p{Alpha}[\\p{Alnum}_]*\\s+" + // type with space, eg.: "int "
"\\p{Alpha}[\\p{Alnum}_]*\\s*=\\s*" + // java identifier with =, eg.: "myVar ="
"(([-+]?\\s*\\d*\\.?\\d+([eE][-+]?\\d+)?[Lf]?)?|" + // numeric non-hex
"(\"[^\"]*\"))\\s*;"; // or unquoted string constant
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
while (m.find()) {
String literal = m.group(1);
System.err.println(literal);
}
https://stackoverflow.com/questions/29050112
复制相似问题