Monday, 23 May 2011

10 Java Regular Expression Examples You Should Know

1. Username Regular Expression Pattern

RegExp:^[a-z0-9_-]{3,15}$ Description:
^ # Start of the line. [a-z0-9_-]# Match characters and symbols in the list, a-z, 0-9 , underscore , hyphen. {3,15}# Length at least 3 characters and maximum length of 15 . $# End of the line.

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class UsernameValidator{ private Pattern pattern; private Matcher matcher; private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$"; public UsernameValidator(){ pattern = Pattern.compile(USERNAME_PATTERN); } /** * Validate username with regular expression * @param username username for validation * @return true valid username, false invalid username */ public boolean validate(final String username){ matcher = pattern.matcher(username); return matcher.matches(); } }

2. Password Regular Expression Pattern

Regex:((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20}) Description:
( # Start of group (?=.*\d) # must contains one digit from 0-9 (?=.*[a-z]) # must contains one lowercase characters (?=.*[A-Z]) # must contains one uppercase characters (?=.*[@#$%]) # must contains one special symbols in the list "@#$%" . # match anything with previous condition checking {6,20} # length at least 6 characters and maximum of 20 ) # End of group

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator{ private Pattern pattern; private Matcher matcher; private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; public PasswordValidator(){ pattern = Pattern.compile(PASSWORD_PATTERN); } /** * Validate password with regular expression * @param password password for validation * @return true valid password, false invalid password */ public boolean validate(final String password){ matcher = pattern.matcher(password); return matcher.matches(); } }

3. Hexadecimal Color Code Regular Expression Pattern

RegExp: ^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$ Description:
^ #start of the line # # must constains a "#" symbols ( # start of group #1 [A-Fa-f0-9]{6} # any strings in the list, with length of 6 | # ..or [A-Fa-f0-9]{3} # any strings in the list, with length of 3 ) # end of group #1 $ #end of the line

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class HexValidator{ private Pattern pattern; private Matcher matcher; private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; public HexValidator(){ pattern = Pattern.compile(HEX_PATTERN); } /** * Validate hex with regular expression * @param hex hex for validation * @return true valid hex, false invalid hex */ public boolean validate(final String hex){ matcher = pattern.matcher(hex); return matcher.matches(); } }

4. Email Regular Expression Pattern

Regex: ^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+ (\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$ Description:
^ #start of the line [_A-Za-z0-9-]+ # must start with string in the bracket [ ], must contains one or more (+) ( # start of group #1 \\.[_A-Za-z0-9-]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #1, this group is optional (*) @ # must contains a "@" symbol [A-Za-z0-9]+ # follow by string in the bracket [ ], must contains one or more (+) ( # start of group #2 - first level TLD checking \\.[A-Za-z0-9]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #2, this group is optional (*) ( # start of group #3 - second level TLD checking \\.[A-Za-z]{2,} # follow by a dot "." and string in the bracket [ ], with minimum length of 2 ) # end of group #3 $ #end of the line

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmailValidator{ private Pattern pattern; private Matcher matcher; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@ [A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; public EmailValidator(){ pattern = Pattern.compile(EMAIL_PATTERN); } /** * Validate hex with regular expression * @param hex hex for validation * @return true valid hex, false invalid hex */ public boolean validate(final String hex){ matcher = pattern.matcher(hex); return matcher.matches(); } }

5. Image File Extension Regular Expression Pattern

([^\s]+(\.(?i)(jpg|png|gif|bmp))$) Description:
( #Start of the group #1 [^\s]+ # must contains one or more anything (except white space) ( # start of the group #2 \. # follow by a dot "." (?i) # ignore the case sensitive checking ( # start of the group #3 jpg # contains characters "jpg" | # ..or png # contains characters "png" | # ..or gif # contains characters "gif" | # ..or bmp # contains characters "bmp" ) # end of the group #3 ) # end of the group #2 $ # end of the string ) #end of the group #1

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class ImageValidator{ private Pattern pattern; private Matcher matcher; private static final String IMAGE_PATTERN = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)"; public ImageValidator(){ pattern = Pattern.compile(IMAGE_PATTERN); } /** * Validate image with regular expression * @param image image for validation * @return true valid image, false invalid image */ public boolean validate(final String image){ matcher = pattern.matcher(image); return matcher.matches(); } }

6.IP Address Regular Expression Pattern

^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\. ([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$ Description:
^ #start of the line ( # start of group #1 [01]?\\d\\d? # Can be one or two digits. If three digits appear, it must start either 0 or 1 # e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9]) | # ...or 2[0-4]\\d # start with 2, follow by 0-4 and end with any digit (2[0-4][0-9]) | # ...or 25[0-5] # start with 2, follow by 5 and end with 0-5 (25[0-5]) ) # end of group #2 \. # follow by a dot "." .... # repeat with 3 time (3x) $ #end of the line

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class IPAddressValidator{ private Pattern pattern; private Matcher matcher; private static final String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; public IPAddressValidator(){ pattern = Pattern.compile(IPADDRESS_PATTERN); } /** * Validate ip address with regular expression * @param ip ip address for validation * @return true valid ip address, false invalid ip address */ public boolean validate(final String ip){ matcher = pattern.matcher(ip); return matcher.matches(); } }

7.Time Format Regular Expression Pattern

(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)-->12-hour ([01]?[0-9]|2[0-3]):[0-5][0-9]-->24-hour
(For 12-Hours) ( #start of group #1 1[012] # start with 10, 11, 12 | # or [1-9] # start with 1,2,...9 ) #end of group #1 : # follow by a semi colon (:) [0-5][0-9] # follow by 0..5 and 0..9, which means 00 to 59 (\\s)? # follow by a white space (optional) (?i) # next checking is case insensitive (am|pm) # follow by am or pm (For 24 HOURS) ( #start of group #1 [01]?[0-9] # start with 0-9,1-9,00-09,10-19 | # or 2[0-3] # start with 20-23 ) #end of group #1 : # follow by a semi colon (:) [0-5][0-9] # follow by 0..5 and 0..9, which means 00 to 59

Example:

a.(12 Hours) import java.util.regex.Matcher; import java.util.regex.Pattern; public class Time12HoursValidator{ private Pattern pattern; private Matcher matcher; private static final String TIME12HOURS_PATTERN = "(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)"; public Time12HoursValidator(){ pattern = Pattern.compile(TIME12HOURS_PATTERN); } /** * Validate time in 12 hours format with regular expression * @param time time address for validation * @return true valid time fromat, false invalid time format */ public boolean validate(final String time){ matcher = pattern.matcher(time); return matcher.matches(); } } b.(24 Hours) import java.util.regex.Matcher; import java.util.regex.Pattern; public class Time24HoursValidator{ private Pattern pattern; private Matcher matcher; private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; public Time24HoursValidator(){ pattern = Pattern.compile(TIME24HOURS_PATTERN); } /** * Validate time in 24 hours format with regular expression * @param time time address for validation * @return true valid time fromat, false invalid time format */ public boolean validate(final String time){ matcher = pattern.matcher(time); return matcher.matches(); } }

8. Date Format (dd/mm/yyyy) Regular Expression Pattern

(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)
( #start of group #1 0?[1-9] # 01-09 or 1-9 | # ..or [12][0-9] # 10-19 or 20-29 | # ..or 3[01] # 30, 31 ) #end of group #1 / # follow by a "/" ( # start of group #2 0?[1-9] # 01-09 or 1-9 | # ..or 1[012] # 10,11,12 ) # end of group #2 / # follow by a "/" ( # start of group #3 (19|20)\\d\\d # 19[0-9][0-9] or 20[0-9][0-9] ) # end of group #3

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class DateValidator{ private Pattern pattern; private Matcher matcher; private static final String DATE_PATTERN = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)"; public DateValidator(){ pattern = Pattern.compile(DATE_PATTERN); } /** * Validate date format with regular expression * @param date date address for validation * @return true valid date fromat, false invalid date format */ public boolean validate(final String date){ matcher = pattern.matcher(date); if(matcher.matches()){ matcher.reset(); if(matcher.find()){ String day = matcher.group(1); String month = matcher.group(2); int year = Integer.parseInt(matcher.group(3)); if (day.equals("31") && (month.equals("4") || month .equals("6") || month.equals("9") || month.equals("11") || month.equals("04") || month .equals("06") || month.equals("09"))) { return false; // only 1,3,5,7,8,10,12 has 31 days } else if (month.equals("2") || month.equals("02")) { //leap year if(year % 4==0){ if(day.equals("30") || day.equals("31")){ return false; }else{ return true; } }else{ if(day.equals("29")||day.equals("30")||day.equals("31")){ return false; }else{ return true; } } }else{ return true; } }else{ return false; } }else{ return false; } } }

9. HTML tag Regular Expression Pattern

<("[^"]*"|'[^']*'|[^'">])*>
< #start with opening tag "<" ( # start of group #1 "[^"]*" # only two double quotes are allow - "string" | # ..or '[^']*' # only two single quotes are allow - 'string' | # ..or [^'">] # cant contains one single quotes, double quotes and ">" ) # end of group #1 * # 0 or more > #end with closing tag ">"

Example:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class HTMLTagValidator{ private Pattern pattern; private Matcher matcher; private static final String HTML_TAG_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; public HTMLTagValidator(){ pattern = Pattern.compile(HTML_TAG_PATTERN); } /** * Validate html tag with regular expression * @param tag html tag for validation * @return true valid html tag, false invalid html tag */ public boolean validate(final String tag){ matcher = pattern.matcher(tag); return matcher.matches(); } }

10.HTML links Regular Expression Pattern

Example:

import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HTMLLinkExtrator{ private Pattern patternTag, patternLink; private Matcher matcherTag, matcherLink; private static final String HTML_A_TAG_PATTERN = ""; private static final String HTML_A_HREF_TAG_PATTERN = "\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))"; public HTMLLinkExtrator(){ patternTag = Pattern.compile(HTML_A_TAG_PATTERN); patternLink = Pattern.compile(HTML_A_HREF_TAG_PATTERN); } /** * Validate html with regular expression * @param html html content for validation * @return Vector links and link text */ public Vector grabHTMLLinks(final String html){ Vector result = new Vector(); matcherTag = patternTag.matcher(html); while(matcherTag.find()){ String href = matcherTag.group(1); //href String linkText = matcherTag.group(2); //link text matcherLink = patternLink.matcher(href); while(matcherLink.find()){ String link = matcherLink.group(1); //link result.add(new HtmlLink(link, linkText)); } } return result; } class HtmlLink { String link; String linkText; HtmlLink(String link, String linkText){ this.link = link; this.linkText = linkText; } @Override public String toString() { return new StringBuffer("Link : ") .append(this.link) .append(" Link Text : ") .append(this.linkText).toString(); } } }

No comments:

Post a Comment