[code="js"]
ab123_c == 'xx_123_ABC'|| a==1 && ttt != “aaa\"'\” || xxx >= 1.12345 && abc==true && ddd==false
[/code]
找出这条语句中的所有变量
[code="js"]
ab123_c == 'xx_123_ABC'|| a==1 && ttt != “aaa\"'\” || xxx >= 1.12345 && abc==true && ddd==false
[/code]
找出这条语句中的所有变量
[code="java"]public class Main {
public static void main(String[] args) throws IOException {
String str = "ab123_c == 'xx_123_ABC'|| a==1 && ttt != \"aaa\"'\" || xxx >= 1.12345 && abc==true && ddd==false";
String variable = "([a-zA-Z_][a-zA-Z0-9_]*)";
String keyword = "(true|false)";
Matcher variableMatcher = Pattern.compile(variable).matcher(str);
while(variableMatcher.find()) {
String var = variableMatcher.group(1);
if(Pattern.matches(keyword, var)) {
continue;
}
int index = str.indexOf(var);
boolean isConstString = false;
do {
if(isConstString(str, str.indexOf(var) - 1)) {
isConstString = true;
break;
}
index = str.indexOf(var, index+1);
} while(index != -1);
if(isConstString) {
continue;
}
System.out.println(var);
}
}
private static boolean isConstString(String str, int index) {
if(index <= 0) {
return false;
}
char c = str.charAt(index);
return c == '\'' || c == '\"';
}
}[/code]
这种方式肯定不好,需要使用如ANTLR 进行词法/语法分析。