简体   繁体   中英

Java - parsing text using delimiter for separating different arguments

How would you use multiple delimiters or a single delimiter to detect and separate out different string matches?

For example, I use a Scanner to parse in the following string:

MrsMarple=new Person(); MrsMarple.age=30;

I would like to separate out this string to determine, in sequence, when a new person is being created and when their age is being set. I also need to know what the age is being set to.

There can be anything between and/or either side of these arguments (there doesn't necessarily have to be a space between them, but the semi-colon is required). The "MrsMarple" could be any word. I would also prefer any arguments following a "//" (two slashes) on the same line to be ignored but that's optional.

If you can think of a simple alternative to using regex I'm more than willing to consider it.

I might try a simple split/loop approach.

Given String input = "MrsMarple=new Person(); MrsMarple.age=30;" :

String[] noComments = input.split("//");
String[] statements = input.split(noComments[0]);
for(String statement: statements) {
    String[] varValue = statement.split("=");
    ...
    // Additional MrsMarple-SmartSense Technology (tm) here...
    ...
}

with judicious use of String.trim() and or other simple tools.

Or to make the the matter more general (and without regexes), you may try scripting (as it looks like a script language syntax): http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/ . Example:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
String input = "MrsMarple=new Person(); MrsMarple.age=30;"
try {
  jsEngine.eval(input);
} catch (ScriptException ex) {
    ex.printStackTrace();
}

In this case you'll need a Java class called Person with public field called age. Above code has not been tested, you may need to add something like

jsEngine.eval("importPackage(my.package);");

to make it work. Anyway, Oracle's tutorial should be helpfull.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM