Monday, October 15, 2012

Check Valid Characters Of a String



import java.util.regex.*;
import java.io.*;

public class CheckString {

    public static void main(String[] args) throws IOException {

        String string = "ashzxcvb13nmasdfg123h.jklopiu123";
        String string2 = "ashzxcvb13nmasdfg.+_-klopiu123";

        CheckString c = new CheckString();
        boolean ok = c.in_required_format(string);
        System.out.println( "in_required_format   :"  + ok);
       
       
       
         ok = c.check_special_char(string2);
        System.out.println( "check_special_char   :"  + ok);

    }

    public boolean check_special_char(String val) {
        boolean in_format = false;
        try {
            Pattern p = Pattern.compile("[+_-]");
            Matcher m = p.matcher(val);
            in_format = m.find();
        } catch (Exception e) {
            System.out.println("ERROR check_special_char" + e.toString());
            in_format = false;
        }
        return in_format;
    }

    public boolean in_required_format(String val) {
        boolean in_format = false;
        try {
            Pattern pattern = Pattern.compile("[A-Za-z0-9.]+");
            Matcher m = pattern.matcher(val);
            in_format = m.matches();
        } catch (Exception e) {
            System.out.println("ERROR in_required_format" + e.toString());
            in_format = false;
        }
        return in_format;
    }
}