Java String Parsing Without Regular Expressions

243 Views Asked by At

From a server, I get strings of the following form:

String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4]    [fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=var7]]]] fixedWord8:fixedWord8";

(only spaces divide groups of word-var pairs) Later, I want to store them in a Hashmap, like myHashMap.put(fixedWord1, var1); and so on.

Problem:
Inside the first "data[......]"-tag, the number of other "data[..........]"-tags is variable, and I don't know the length of the string in advance.

I don't know how to process such Strings without resorting to String.split(), which is discouraged by our assignment task givers (university).

I have searched the internet and couldn't find appropriate websites explaining such things.
It would be of great help, if experienced people could give me some links to websites or something like a "diagrammatic plan" so that I could code something.

EDIT: got mistake in String (off-topic-begin "please don't lynch" off-topic-end), the right string is (changed fixedWord7=var7 ---to---> fixedWord7=[var7]):

String x = "fixedWord1:var1 data[[fixedWord2:var2 fixedWord3:var3 data[[fixedWord4]    [fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]] , [fixedWord2:var2 fixedWord3:var3 data[[fixedWord4][fixedWord5=var5 fixedWord6=var6 fixedWord7=[var7]]]]] fixedWord8:fixedWord8";
2

There are 2 best solutions below

6
Don On BEST ANSWER

I assume your string follows a same pattern, which has "data" and "[", "]" in it. And the variable name/value will not include these strings

  1. remove string "data[", "[", "]", and "," from the original string

    replaceAll("data[", "")
    replaceAll("[", "")
    etc
    
  2. separate the string by space: " " by using StringTokenizer or loop through the String char by char.

  3. then you will get array of strings like

    fixedWorld1:var1
    fixedWorld2:var2
    ......
    fixedWorld4
    fixedWorld5=var5
    ......
    
  4. then again separate the sub strings by ":" or "=". and put the name/value into the Map
1
anubhava On

Problem is not absolutely clear but may be something like this will work for you:

Pattern p = Pattern.compile("\\b(\\w+)[:=]\\[?(\\w+)");
Matcher m = p.matcher( x );
while( m.find() ) {
   System.out.println( "matched: " + m.group(1) + " - " + m.group(2) );
   hashMap.put ( m.group(1), m.group(2) );
}