Applying regex patterns – In java and javascript

Regex patterns are easier to write than to read. Analysing the following regex patterns might give a good idea of how to come up with meaningful regex patterns:


All alphabets

^[a-zA-Z]*$

All digit

^[0-9]*$

All alphabets+digits

^[0-9a-zA-Z]*$

Email format

^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$

Integers or decimals rounded to last two digits

^[0-9]+[.]?[0-9]{0,2}$

should be alphabets+digits with enclosed space

^[0-9a-zA-Z]+[0-9a-zA-Z\\s]*$

Can consist of Characters,space,dash,dot,pound,slash,quote

^[0-9a-zA-Z\\s\\-.#\\/’]*$

Can consist space,dash,quote

^[0-9a-zA-Z\\s\\-‘]*$

Can have 5 or 9 digits or; 10 digits when dash is included

^(d{5}|d{9}|d{5}-d{4})$
for example ZIP

Format for phone (US)

^([(]{1}[0-9]{3}[)]{1}[.| |-]{0,1}|^[0-9]{3}[.|-| ]?)?[0-9]{3}(.|-| )?[0-9]{4}$

should have 9 Digits and can have one dash
for instance TAXID

^[0-9]{9}$ (method to validate this in java below)

Should have 9 Digits

^[0-9]{9}$
For example SSN

private static boolean checkTAXID(String val) {
        boolean flag = false;
        String[] t = val.split("-");
        if (t.length < 2) {
            if (checkRegExp(val, "^[0-9]{9}$")) {
                flag = true;
            }
        }
        if (t.length == 2) {
            if ((val.length() == 10) && checkRegExp(t[0], "^[0-9]*$")
                    && checkRegExp(t[1], "^[0-9]*$")) {
                flag = true;
            }
        }
        if (t.length > 2) {
            flag = false;
        }
        return flag;
    }
 Below is a java method to validate the regular expresssions above:
	private static boolean checkRegExp(String val, String regExp) {
		 boolean flag = false;
		 if (null != val && !val.trim().equals("")) {
		 flag = val.matches(regExp);
		 }
		 return flag;
		 }

Here is a utility method to validate dates in various formats using regular expressions to recognize patterns and the SimpleDateFormat class to validate further:

public static final String returnedDateFormatString = "MM/dd/yyyy";

public static String validateDate(String paramDate) {
    DateFormat returnedDateFormat = new SimpleDateFormat(
            returnedDateFormatString);
    String regExp1 = "^[0-1]\\d[0-3]\\d[1-2]\\d{3}$";
    // -- matches MMDDYYYY
    String regExp2 = "^[0-1]*\\d[/.][0-3]*\\d[/.][1-2][\\d]{3}$";// --
    // matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
    String regExp3 = "^[0-1]*\\d[/.][0-3]*\\d[/.][\\d]{2}$";
    // (matches MM/DD/YY)(with or without leading zeroes for MM and DD)
    String regExp4 = "^[1-2][\\d]{3}[/.][0-1]*\\d[/.][0-3]*\\d$";
    // matches YYYY/MM/DD (with or without/ leading zeroes for MM and DD)
    String regExp5 = "^t$";// -- matches t
    String regExp6 = "^t[\\+\\-][\\d]+$";// -- matches t-# and t+#
    DateFormat dateFormat = null;
    Date date = null;
    if (checkRegExp(paramDate, regExp1)) {
        dateFormat = new SimpleDateFormat("MMddyyyy");
        try {
            date = dateFormat.parse(paramDate);
            if (dateFormat.format(date).equals(paramDate)) {
                return returnedDateFormat.format(date);
            }
        } catch (ParseException e) {
            date = null;
        }

    } else if (checkRegExp(paramDate, regExp2)) {
        String dateFormatArray[] = { "MM/dd/yyyy", "MM/d/yyyy",
                "M/dd/yyyy", "M/d/yyyy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yyyy", "MM.d.yyyy",
                "M.dd.yyyy", "M.d.yyyy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp3)) {
        String dateFormatArray[] = { "MM/dd/yy", "MM/d/yy", "M/dd/yy",
                "M/d/yy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yy", "MM.d.yy", "M.dd.yy",
                "M.d.yy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp4)) {
        String dateFormatArray[] = { "yyyy/MM/dd", "yyyy/MM/d",
                "yyyy/M/dd", "yyyy/M/d" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "yyyy.MM.dd", "yyyy.MM.d",
                "yyyy.M.dd", "yyyy.M.d" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    }
    return null;
}

Corresponding javascript method to validate regex:

function executePattern(val, regex) {
            var flg = false;
            var re = new RegExp(regex);
            if (val.length > 0 && !val.match(re)) {
                flg = true;
            }
            return flg;
        }

Here are some explanations for a few regex patterns:

^[0-1]d[0-3]d[1-2]d{3}$|^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3}$|^[0-1]*d[/.][0-3]*d[/.][d]{2}$|^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d$|^t$|^t[+-][d]+$

break up to explaining the pieces
^[0-1]d[0-3]d[1-2]d{3}$ — matches MMDDYYYY
^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3} — matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
^[0-1]*d[/.][0-3]*d[/.][d]{2} — matches MM/DD/YY (with or without leading zeroes for MM and DD)
^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d — matches YYYY/MM/DD (with or without leading zeroes for MM and DD)
^t — matches t
^t[+-][d]+$ — matches t-# and t+#
http://regexpal.com/ is a good site to see how your regex patterns match input data.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: