Friday, June 3, 2011

regex sample for numeric check

This is a sample to check if the String contained is a numeric value or not by doing pattern matching using regex in java.


package com.practice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Junk
{
  public static void main(String[] args)
  {
      String a = "12.0"; //Valid
      String b = "12.5"; //Invalid

      Pattern p = Pattern.compile( "([0-9]*)\\.[0]" );

      Matcher m = p.matcher(a);
      m.matches(); //TRUE

      Matcher m2 = p.matcher(b);
      m2.matches(); //FALSE
   }
 
}

No comments:

Post a Comment