Domanda

I've been implementing an application to retrieve a word inside a incoming String parameter, this String parameter can vary since it is an URL, but the pattern for almost all the incoming url's is the same. For instance I could have:

GET /com.myapplication.v4.ws.monitoring.ModuleSystemMonitor HTTP/1.1

or

GET /com.myapplication.filesystem.ws.ModuleFileSystem/getIdFolders/jsonp?idFolder=idFis1&callback=__gwt_jsonp__.P0.onSuccess&failureCallback=__gwt_jsonp__.P0.onFailure HTTP/1.1

So in any case, I want to extract the word that starts with Module, for example, for the first incoming parameter I want to get: ModuleSystemMonitor. And for the second one I want to get the word: ModuleFileSystem.

This is the requirement, I'm not allowed to do anything else but this: just a method that receives a line and try to extract the words I mentioned: ModuleSystemMonitor and ModuleFileSystem.

I've been thinkng of using StringTokenizer class or String#split method, but I'm not sure if they are the best option. I tried and it is easy to get the word begins with Module using indexOf, but how to cut the word if from some cases it comes with a white space like the first sample or it comes with a "/" (slash) in the second. I know I can make an "if" statement and cut it when it is white space or it is slash but I wonder to know if there is another way that could be more dynamic.

Thanks in advance for your time and help. Best regards.

È stato utile?

Soluzione

I'm not sure this is the best solution but you could try this:

String[] tmp = yourString.Split("\\.|/| ");
for (int i=0; i< tmp.length(); i++) {
    if (tmp[i].matches("^Module.*")) {
       return tmp[i];
    }
}
return null;

Altri suggerimenti

You can just use String.indexOf and String.substring like this:

int startIndex = url.indexOf("Module");    

for (int index = startIndex + "Module".length; i < url.length; i++
{
  if (!Character.isLetter(url.charAt(index)) 
  {
    return url.substring(startIndex, index));
  }
}

Based on the assumption that the first non-letter character is the end marker of the word.

String stringToSearch = "GET /com.myapplication.v4.ws.monitoring.ModuleSystemMonitor    HTTP/1.1";
Pattern pattern = Pattern.compile("(Module[a-zA-Z]*)");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()){
        System.out.println(matcher.group(1));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top