I have this piece of code where I insert a Pattern key and a String token to a hashmap:
while( (word = reservedWordsRead.readLine()) != null ) {
String[] k = word.split(" ");
infoList.put(Pattern.compile("^("+k[0]+")"), //lexeme
k[1]); //token
}
It reads from a file that goes like this:
) rparen
( lparen
and but the parentheses aren't recognized so I modified the file to look like this:
\\) rparen
\\( lparen
and the code like this:
while( (word = reservedWordsRead.readLine()) != null ) {
String[] k = word.split(" ");
infoList.put(Pattern.compile("^("+Pattern.quote(k[0])+")"), //lexeme
k[1]); //token
}
But I don't get the proper output. It doesn't match anything. Also, the rparen and lparen are inserted in the hashmap because I am able to print the following using my tokenizer() method:
pattern: ^(\Q\\)\E), token: rparen
pattern: ^(\Q\\(\E), token: lparen
This is my tokenizer method:
public void tokenize(String str) {
String s = str.trim();
tokenList.clear();
while (!s.equals("")) {
boolean match = false;
for ( Entry<Pattern,String> thing: infoList.entrySet() ) {
System.out.println("pattern: "+thing.getKey().toString()+", token: "+thing.getValue());
Matcher m = thing.getKey().matcher(s);
if (m.find()) {
match = true;
String tok = m.group().trim();
s = m.replaceFirst("").trim();
tokenList.put(tok,thing.getValue());
break;
}
} if (!match)
throw new ParserException("Unexpected character in input: "+s);
}
}
I'm not sure what I'm doing wrong.. Gladly appreciate your help :)