# HTTP request path parser

I have written a method to tokenize HTTP request paths such as /employee/23/edit:

protected void compile(String path){
int mark=0;
for(int i=0; i<path.length(); ++i){
if(path.charAt(i)==DELIM){
if(mark!=i)
mark=i+1;
}
else if(path.length()==i+1){
}
}
}


And a method to tokenize the consumer of these paths such as /employee/[id]/edit:

protected void compile(String path){
int mark=0;
boolean wild=false;
for(int i=0; i<path.length(); ++i){
if(!wild){
if(path.charAt(i)==DELIM){
if(mark!=i)
mark=i+1;
}
else if(path.length()==i+1){
}
else if(path.charAt(i)=='['){
wild=true;
}
}
else if(path.charAt(i)==']'){
wild=false;
mark=i+1;
}
}
}


The idea here is that there will be an implicit variable called id with the value 23. However, that isn't here nor there. How does my approach look? Can it be improved? Also: DELIM = '/'.

This is more-or-less an exercise in writing a parser, which is why I didn't use String#split().

• Wouldn't String.split() work better for tokenizing a String (download.oracle.com/javase/1.4.2/docs/api/java/lang/…)? Jan 20 '11 at 18:23
• It looks like anything between the last / and an opening [ will be ignored. Is that intentional? Jan 20 '11 at 18:26
• @shambleh: This was more or less an exercise in writing a simple parser. I anticipate it becoming more complicated over time where String#split() wont suffice. Jan 20 '11 at 18:28
• It also seems weird to me that you're just discarding the names of the variables like that. Though without knowing how you'll use the result of the compile method, it's hard to say whether it's bad or not. Jan 20 '11 at 18:44
• @sepp2k: For sake of posting less code, you don't see anything more than the parsing aspect. I took out the part you are referring to. Jan 20 '11 at 18:54

Your first compile method can be replaced by a single call to String.split.
Assuming the intended behavior for the second compile method is such that "/foo/b[a]r/baz" will compile to {"foo", "?", "baz"}, it can be replaced by a call to split and then iterating over the result and replacing any string the includes square brackets with "?".
If the intended behavior is rather that it will compile to {"foo", "b", "?", "r", "baz"}, you can first replace [anything] by /?/ using String.replace and then use String.split.
• I have to disagree about the variable names, unless you can suggest better ones? mark is a perfectly valid in my opinion because it is marking a point in the string. I could change wild to isWild I suppose. As for handling question marks, no, the purpose for the paths with wildcards is to be parsed on the server when the web application starts up. I intend to annotate a method like this: @Get("/employees/[id]"). I am just dealing with paths, not the query string. Jan 20 '11 at 19:59