samedi 6 février 2016

How can I match a regex in a switch statement?

I'm trying to match tokens against a switch statement in a function, and one of those tokens needs to be able to identify a string or a digit. How can do I do that?

public Token analyzeToken(String token) {
      Token tokenType = null;     

      switch (token) {

         case "STRING":
            Pattern p = Pattern.compile("[a-z]+");
            Matcher m = p.matcher(token);
            if(m.matches()) {
               tokenType = Token.STRING;
               break;
            }
         case "NUMBER":
            Pattern p = Pattern.compile("[0-9]+");
            Matcher m = p.matcher(token);
            if(m.matches()) {
               tokenType = Token.NUMBER;
               break;

         default:
            tokenType = TOKEN.UNKNOWN;
            break;

      }
   }

Aucun commentaire:

Enregistrer un commentaire