Java - parsing text using delimiter for separating different arguments

末鹿安然 提交于 2019-12-02 20:15:44

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11743686/java-parsing-text-using-delimiter-for-separating-different-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!