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)
tokens.add(path.substring(mark,i));
mark=i+1;
}
else if(path.length()==i+1){
tokens.add(path.substring(mark,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)
tokens.add(path.substring(mark,i));
mark=i+1;
}
else if(path.length()==i+1){
tokens.add(path.substring(mark,i+1));
}
else if(path.charAt(i)=='['){
wild=true;
}
}
else if(path.charAt(i)==']'){
tokens.add("?");
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().
/and an opening[will be ignored. Is that intentional? \$\endgroup\$String#split()wont suffice. \$\endgroup\$