title: input Pattern matching java
body: <p>I want to write a function <code>validate()</code> which will take some pattern or regular expression as argument and will ask user to input its choice. If the choice matches the pattern, it will return the choice, otherwise it will ask user to re-enter the choice.</p>
  
  <p>For example if I call <code>validate()</code> with <code>123</code> as argument, it will return either <code>1</code> or <code>2</code> or <code>3</code> depending upon user input.</p>
  
  <p>But I don't know how patterns or regular expressions are used. Please help.</p>
  
  <p>I have written some code but I am not sure what to write at a couple of places.
  I want the validate function written below to accept the input either 1 or 2 or 3 and return the same.</p>
  
  <pre><code>import java.io.*;
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  class Pat
  {
    public static void main(String args[])
    {
      int num=validate(Pattern.compile("123"));//I don't know whether this is right or not
      System.out.println(num);
    }
    static int validate(Pattern pattern)
    {
      int input;
      boolean validInput=false;
      do
      {
        try
        {
          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
          input=Integer.parseInt(br.readLine());
          validInput=true;
        }catch(Exception e)
        {
          System.out.println(""+e);
        }
      }while(!validInput || input.matches(pattern));// This also seems like a problem.
      return input;
    }
  }
  </code></pre>