1 Reply Latest reply: Jul 3, 2014 2:00 AM by PhHein RSS

    Pattern matches in java

    Tshifhiwa

      hi i have code which validate code enter by user

      the requirement say the maxlength=2 and minlength=1 and is a string

      the user can enter code as follows

      00

      A1

      HH

      12

      10

      09

       

      I have this code

      public boolean isValidPattern(String s_value, String s_pattern)

          {

              boolean flag = false;

       

              if (Pattern.matches(s_pattern, s_value))

              {

                  flag = true;

              }

       

              return flag;

          }

       

      if (!isValidPattern(code, "[0-9X]{1,2}"))

                  {

                 

                  if(!isValidPattern(code, "[A-Z]{1,2}"))  

                    

                  {

                     System.out.println("wrong patten code ");

                  }

       

      my problem is when i put

      A1 is still giving error

        • 1. Re: Pattern matches in java
          PhHein

          You only need to test once. In your code you first test whether "A1" is one or two chars out of 0-9 and X, which is false and the next match tests for one or two chars out of A-Z which is also false.

          All you need is:

          if(!Pattern.matches(code, "[0-9A-Z]{1,2}")) {
              System.out.println("wrong patten code ");
          }