title: Validate a string contains only certain characters in java
body: <p>Ok, what I am trying to do is take a user input in infix notation and translate it to postfix and then evaluate it. I have that already completed.</p>
  
  <p>What I am struggling with, is for the user input I need to validate that it only contains the following: (), 0-9, +, -, *, /, % </p>
  
  <p>Each character will be separated by a space, so here is a potential valid input:</p>
  
  <p>( 3 + 4 ) * 5 / ( 6 - 7 )</p>
  
  <p>I have created an InvalidCharacterException that I wish to throw if the user string contains anything other than those characters.</p>
  
  <p>Here is what an invalid input would look like:</p>
  
  <p>3 - 5 ^ 5</p>
  
  <p>The ^ would be an invalid character and then I would throw new InvalidCharacterException and ask for a new input.</p>
  
  <p>I will also say I have looked at a ton of regex samples, and to be honest I don't understand what they're doing.</p>
  
  <p>EDIT:</p>
  
  <p>Ok, this is what I ended up implementing because I don't really understand anything else. Any advice on a simpler way?</p>
  
  <pre><code>    for(int i = 0; i &lt;= infix.length(); i++){
          if(infix.charAt(i) ==  '(' || infix.charAt(i) == ')' || infix.charAt(i) =='+' 
                  || infix.charAt(i) =='-' ||infix.charAt(i) == '*' ||infix.charAt(i) == '/'
                  ||infix.charAt(i) == '%' ||infix.charAt(i) ==' ' ||infix.charAt(i) == '0' 
                  ||infix.charAt(i) == '1' || infix.charAt(i) =='2' || infix.charAt(i) =='3' 
                  ||infix.charAt(i) == '4' ||infix.charAt(i) == '5' ||infix.charAt(i) == '6' 
                  ||infix.charAt(i) == '7' || infix.charAt(i) =='8' ||infix.charAt(i) == '9'){
  
          }else{
              throw new InvalidCharacterException(infix.charAt(i));
          }
  
      }
  </code></pre>
  
  <p>Infix is the variable name of my user input as a StringBuffer.</p>