001: package util;
002:
003: import java.io.*;
004: import java.util.*;
005: import org.apache.oro.text.regex.*;
006: import org.apache.oro.text.perl.*;
007:
008: public class NameValueParser {
009: Map ht = null;
010: MultipleMatchModel mmm;
011: String regexp;
012:
013: public static void main(String args[]) {
014: NameValueParser t = new NameValueParser();
015: try {
016: t.mmm = createMultipleMatchModel();
017: /*
018: PerlWrapper.getMultipleMatches(
019: "(?:(\\w+)=(\\S+))",
020: "lines=rett append=true dothis=aaa ", t.mmm);
021: */
022:
023: PerlWrapper.getMultipleMatches("(?:(\\w+)=(\\S+))",
024: "read a.txt lines=1,134 append=true dothis=aaa",
025: t.mmm);
026:
027: } catch (MalformedPatternException exc) {
028: System.err.println("EXC:" + exc.toString());
029: }
030:
031: t.ht = (Map) t.mmm.getObject();
032: System.out.println("lines:" + t.getValue("lines"));
033: System.out.println("append:" + t.getValue("append"));
034: System.out.println("dothis:" + t.getValue("dothis"));
035: System.out.println("hta:" + t.getValue("hta"));
036: System.out.println("htb:" + t.getValue("htb"));
037:
038: System.out.println("keys...");
039: Iterator e = t.ht.keySet().iterator();
040: while (e.hasNext())
041: System.out.println(e.next());
042: System.out.println("values...");
043: e = t.ht.values().iterator();
044: while (e.hasNext())
045: System.out.println(e.next());
046:
047: }
048:
049: /** create default name value parser, using default regexp */
050: public NameValueParser() {
051: mmm = createMultipleMatchModel();
052: regexp = "(?:(\\w+)=(\\S+))";
053: }
054:
055: /** create name value parser with customized Model */
056: public NameValueParser(MultipleMatchModel mmmp) {
057: mmm = mmmp;
058: regexp = "(?:(\\w+)=(\\S+))";
059: }
060:
061: /** set your own regexp, to override default one */
062: public void setRegexp(String reg) {
063: regexp = reg;
064: }
065:
066: /** get Hash table or other object based on your mmm, after parsing
067: * given line. Returns null if your regexp was malformed */
068: public Object getResults(String line) {
069: // we should compile and keep this regexp.
070: try {
071: PerlWrapper.getMultipleMatches(regexp, line, mmm);
072: } catch (MalformedPatternException exc) {
073: System.err.println("EXC:" + exc.toString());
074: return null;
075: }
076: return mmm.getObject();
077: }
078:
079: public static MultipleMatchModel createMultipleMatchModel() {
080: return new MultipleMatchModel() {
081: Map ht = new HashMap();
082: String key;
083:
084: public void setValueAt(String s, int row, int group) {
085: //System.out.println(s+":"+ row+":"+group);
086: if (group == 1)
087: key = s;
088: else if (group == 2)
089: ht.put(key, s);
090: }
091:
092: public String getValueAt(int row, int group) {
093: return null;
094: }
095:
096: public Object getObject() {
097: return ht;
098: }
099:
100: };
101:
102: }
103:
104: public String getValue(String varname) {
105: return (String) ht.get(varname);
106: }
107:
108: }
|