admin管理员组

文章数量:1430093

I have a Java String that contains javascript code, and i need to extract all the javascript vars' names.

So, for the following javasctipt:

var x;
var a,b,c,d;
var y = "wow";
var z = y + 'x';

I need to get "x,a,b,c,d,y,z" as a result.

I dont need to get their values, just their names.

I have a Java String that contains javascript code, and i need to extract all the javascript vars' names.

So, for the following javasctipt:

var x;
var a,b,c,d;
var y = "wow";
var z = y + 'x';

I need to get "x,a,b,c,d,y,z" as a result.

I dont need to get their values, just their names.

Share Improve this question edited Dec 29, 2011 at 11:49 poitroae asked Nov 16, 2011 at 11:34 poitroaepoitroae 21.4k10 gold badges64 silver badges81 bronze badges 3
  • 1 Do you mean like reading a file containing javasscript in java? – Johan Sjöberg Commented Nov 16, 2011 at 11:38
  • I think what you are asking is answered in stackoverflow./questions/2051678/… – Niranga Commented Nov 16, 2011 at 11:38
  • so, you have a Java String variable that contains javascript code, and you need to extract the names of all javascript vars? – Ahmad Y. Saleh Commented Nov 16, 2011 at 11:39
Add a ment  | 

3 Answers 3

Reset to default 4

Well you can try and get the bindings that the execution of the script creates:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine se = mgr.getEngineByName("JavaScript");

try {
    se.eval("var x;var a,b,c,d;var y = \"wow\";var z = y+'x';");
    Bindings bindings = se.getBindings(ScriptContext.ENGINE_SCOPE);
    System.out.println(bindings.keySet());
}
catch (ScriptException e) {
    //e.printStackTrace();
}

this prints [d, b, c, println, a, context, z, y, print, x]

as you see some extra bindings are defined: context, print and println

and here we filter them out

Set<String> keySet = bindings.keySet();
keySet.removeAll(Arrays.asList("context", "print", "println"));
System.out.println(keySet);

this prints [d, b, c, a, z, y, x]

Something like the following:

List<String> vars = new ArrayList<String>();

Pattern p = Pattern.pile("^\\s*var\\s+(.*?)\\s*;?$");

BifferedReader reader = .... // create the reader
String line = null;
while ((line = reader.readLine()) != null) {
    Matcher m = p.matcher(line);
    if (m.find()) {
        vars.addAll(Arrays.asList(m.group(1).split("\\s*,\\s*")));       
    }
}

Please note that I wrote this code without IDE and have never piled and ran it. So, sorry for possible bugs but I thing it is readable enough and can be a good starting point for you.

I'm not sure whether this would be too convoluted, but I would probably get the BNF for Javascript (see SO: Repository of BNF Grammars?) and then use something like ANTLR to create a parser for Javascript, which you can then use to extract all the variables based on the Javascript source code. See also SO: ANTLR Tutorials.

本文标签: Parsing JavaScript code in Java to retrieve variables39 namesStack Overflow