private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$"; * Validate username with regular expression * @param username username for validation * @return true valid username
Trang 1Java regular expression
1 How to validate username with regular expression
Remember:
Username Regular Expression Pattern
^ a z0- _ ]{ 3 15 }
Description
^ # Start of the line
[ -z0- _ ] # Match characters and symbols in the list, a-z, 0 9, underscore, hyphen { ,15 } # Length at least 3 characters and maximum length of 15
$ # End of the line
Whole combination is means, 3 to 15 characters with any lower case character, digit or special symbol “_-” only This is common username pattern that’s widely use in different websites.
pattern=Pattern.compile( USERNAME_PATTERN);
}
matcher=pattern.matcher(username);
}
}
TestUsernameValidator.java
Trang 2public class TestUsernameValidator {
usernameValidator=new UsernameValidator();
}
return new Object[]{"mkyong34", "mkyong_2002",2002" ,"mk3-4_yong"};
"mkyong-}
return new Object[]{"mk","mk@yong","mkyong123456789_-"};
}
}
this.usernameValidator = usernameValidator;
}
TestUsernameValidator test=new TestUsernameValidator();
}
Result:
mkyong34:true
Trang 3underscore, hyphen
$ # End of the line
Whole combination is means, 3 to 15 characters with any lower case character, digit or special symbol “_-” only This is common username pattern that’s widely use in different websites.
1 Java Regular Expression Example
UsernameValidator.java
Trang 4private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
* Validate username with regular expression
* @param username username for validation
* @return true valid username, false invalid username
*/
3 Username that doesn’t match:
1 mk (too short, min 3 characters)
2 mk@yong (“@” character is not allow)
3 mkyong123456789_- (too long, max characters of 15)
4 Unit Test – UsernameValidator
Using testNG to perform unit test.
Trang 5@DataProvider
boolean valid = usernameValidator.validate(temp)
System.out.println("Username is valid : " temp + " , "
boolean valid = usernameValidator.validate(temp)
System.out.println("username is valid : " temp + " , "
5 Unit Test – Result
Trang 6username is valid : mkyong123456789_- , false
( ?= \d ) # must contains one digit from 0 9
( ?= [ - ]) # must contains one lowercase characters
( ?= [ - ]) # must contains one uppercase characters
( ?= [ @#$ % ]) # must contains one special symbols in the list "@#$%"
# match anything with previous condition checking
{ , 20} # length at least 6 characters and maximum of 20
Trang 7public class PasswordValidator {
=.*[A-Z])(?=.*[@#$%]).{6,20})";
pattern=Pattern.compile( USERNAME_PATTERN);
}
matcher=pattern.matcher(username);
passwordvalidator=new PasswordValidator();
}
return new Object[]{"mkyong1A@", "mkYOn12$"};
}
return new Object[]{"mY1A@","mkyong12@","mkyoNg12*","mkyonG$
this.passwordvalidator = passwordvalidator;
}
TestPasswordValidator test=new TestPasswordValidator();
Trang 9((?= \d)(?= [ - ])(?= [ - ])(?= [@#$%]) 6 20})
Description
P.S The grouping formula order is doesn’t matter.
1 Java Regular Expression Example
PasswordValidator.java
* Validate password with regular expression
* @param password password for validation
* @return true valid password, false invalid password
*/
Trang 102 Password that match:
1 mkyong1A@
2 mkYOn12$
3 Password that doesn’t match:
1 mY1A@ , too short, minimum 6 characters
2 mkyong12@ , uppercase characters is required
3 mkyoNg12* , special symbol “*” is not allow here
4 mkyonG$$, digit is required
5 MKYONG12$ , lower case character is required
4 Unit Test – PasswordValidator
Unit test with TestNG
@BeforeClass
@DataProvider
Trang 11boolean valid = passwordValidator.validate(temp)
System.out.println("Password is valid : " temp + " , "
boolean valid = passwordValidator.validate(temp)
System.out.println("Password is valid : " temp + " , "
5 Unit Test – Result
Password is valid : mkyong1A@ , true
Password is valid : mkYOn12$ , true
Password is valid : mY1A@ , false
Password is valid : mkyong12@ , false
Password is valid : mkyoNg12* , false
Password is valid : mkyonG$$ , false
Password is valid : MKYONG12$ , false
Trang 123.How to validate Hex color code with regular expression.
Remenber:
Hexadecimal Color Code Regular Expression Pattern
^ ([A Fa-f0- ]{6 | A Fa-f0- ]{3})$
Description
Whole combination is means, string must start with a “#” symbol , follow by a letter from “a” to
“f”, “A” to “Z” or a digit from “0″ to 9″ with exactly 6 or 3 length This regular expression pattern is very useful for the Hexadecimal web colors code checking.
{3})$";
pattern=Pattern.compile( HEX_PATTERN);
}
matcher=pattern.matcher(hex);
}
}
Trang 13hexColorValidator=new HexColorValidator();
}
return new Object[]{"#1f1f1F", "#AFAFAF","#1AFFa1","#222fff",
"#F00"};
}
return new Object[]{"mY1A@","mkyong12@","mkyoNg12*","mkyonG$
this.hexColorValidator = hexColorValidator;
}
TestHexColorValidator test=new TestHexColorValidator();
Trang 15^ ([A Fa-f0- ]{6 | A Fa-f0- ]{3})$
Description
Whole combination is means, string must start with a “#” symbol , follow by a letter from “a” to
“f”, “A” to “Z” or a digit from “0″ to 9″ with exactly 6 or 3 length This regular expression pattern is very useful for the Hexadecimal web colors code checking.
Java Regular Expression Example
* Validate hex with regular expression
* @param hex hex for validation
* @return true valid hex, false invalid hex
*/
}
Hex code that match:
1 “#1f1f1F”, “#AFAFAF”,”#1AFFa1″,”#222fff”, “#F00″, “#F00″
Trang 16Hex code that doesn’t match:
1 “123456″ – must start with a “#” symbol
2 “#afafah” – “h” is not allow, valid letter from “a” to “f”
3 “#123abce” – either 6 length or 3 length
4 “aFaE3f” – must start with a “#” symbol, either 6 length or 3 length
5 “F00″ – must start with a “#” symbol
6 “#afaf” – either 6 length or 3 length
7 “#F0h” – “h” is not allow, valid letter from “a” to “f”
Unit Test – HexValidator
@BeforeClass
@DataProvider
@DataProvider
Trang 17for(String temp : hex){
boolean valid = hexValidator.validate(temp)
System.out.println("Hex is valid : " temp + " , "
boolean valid = hexValidator.validate(temp)
System.out.println("Hex is valid : " temp + " , "
Unit Test – Result
Hex is valid : #1f1f1F , true
Hex is valid : #AFAFAF , true
Hex is valid : #1AFFa1 , true
Hex is valid : #222fff , true
Hex is valid : #F00 , true
Hex is valid : 123456 , false
Hex is valid : #afafah , false
Hex is valid : #123abce , false
Hex is valid : aFaE3f , false
Hex is valid : F00 , false
Hex is valid : #afaf , false
Hex is valid : #F0h , false
Trang 184.How to validate email address with regular expression.
The combination means, email address must start with “_A-Za-z0-9-\\+” , optional follow by “ [_A-Za-z0-9-]“, and end with a “@” symbol The email’s domain name must start with “A-Za- z0-9-”, follow by first level Tld (.com, net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, com.my) “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.
Trang 19private static final String EMAIL_PATTERN=Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern=Pattern.compile( EMAIL_PATTERN);
}
matcher=pattern.matcher(email);
emailValidator=new EmailValidator();
}
return new Object[]{ "mkyong@yahoo.com",
return new Object[]{ "mkyong", "mkyong@.com.my",
Trang 20public EmailValidator getEmailValidator() {
}
this.emailValidator = emailValidator;
}
TestEmailValidator test=new TestEmailValidator();
Trang 22[_A-Za-z0- -\\+ + # must start with string in the bracket [ ], must
The combination means, email address must start with “_A-Za-z0-9-\\+” , optional follow by “ [_A-Za-z0-9-]“, and end with a “@” symbol The email’s domain name must start with “A-Za- z0-9-”, follow by first level Tld (.com, net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, com.my) “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.
1 Java Regular Expression Example
Here’s a Java example to show you how to use regex to validate email address.
EmailValidator.java
Trang 23* @return true valid hex, false invalid hex
*/
}
}
2 Valid Emails
1 mkyong@yahoo.com, mkyong-100@yahoo.com, mkyong.100@yahoo.com
2 mkyong111@mkyong.com, mkyong-100@mkyong.net, mkyong.100@mkyong.com.au
3 mkyong@1.com, mkyong@gmail.com.com
4 mkyong+100@gmail.com, mkyong-100@yahoo-test.com
3 Invalid Emails
1 mkyong – must contains “@” symbol
2 mkyong@.com.my – tld can not start with dot “.”
3 mkyong123@gmail.a – “.a” is not a valid tld, last tld must contains at least two characters
4 mkyong123@.com – tld can not start with dot “.”
5 mkyong123@.com.com – tld can not start with dot “.”
6 .mkyong@mkyong.com – email’s first character can not start with dot “.”
7 mkyong()*@gmail.com – email’s is only allow character, digit, underscore and dash
8 mkyong@%*.com – email’s tld is only allow character and digit
9 mkyong 2002@gmail.com – double dots “.” are not allow
10 mkyong.@gmail.com – email’s last character can not end with dot “.”
11 mkyong@mkyong@gmail.com – double “@” is not allow
12 mkyong@gmail.com.1a -email’s tld which has two characters can not contains digit
Trang 24private EmailValidator emailValidator;
@BeforeClass
}
@DataProvider
for (String temp : Email) {
boolean valid = emailValidator.validate(temp)
System.out.println("Email is valid : " temp + " , " +
}}
"ValidEmailTest")
for (String temp : Email) {
boolean valid = emailValidator.validate(temp)
System.out.println("Email is valid : " temp + " , " +
}}
}
Here’s the unit test result.
Trang 25Email is valid : mkyong@yahoo.com , true
Trang 26Whole combination is means, must have 1 or more strings (but not white space), follow by dot
“.” and string end in “jpg” or “png” or “gif” or “bmp” , and the file extensive is case-insensitive This regular expression pattern is widely use in for different file extensive checking You can
just change the end combination (jpg|png|gif|bmp) to come out different file extension checking
that suit your need.
gif|bmp))$)";
pattern=Pattern.compile( IMAGE_PATTERN);
}
matcher=pattern.matcher(image);
Trang 27public class TestImageValidator {
imageValidator=new ImageValidator();
}
"a.jpg", "a.gif","a.png", "a.bmp", " jpg", " gif"," png", " bmp", "a.JPG", "a.GIF","a.PNG", "a.BMP", "a.JpG", "a.GiF","a.PnG", "a.BmP", "jpg.jpg", "gif.gif","png.png", "bmp.bmp" };
}
".jpg", ".gif",".png",".bmp", " jpg", " gif"," png"," bmp", "a.txt", "a.exe","a.","a.mp3",
this.imageValidator = imageValidator;
}
TestImageValidator test=new TestImageValidator();
Trang 28System.out.println(objectInvalid[i]+":"+valid);
}}
Trang 29How to validate image file extension with
Whole combination is means, must have 1 or more strings (but not white space), follow by dot
“.” and string end in “jpg” or “png” or “gif” or “bmp” , and the file extensive is case-insensitive This regular expression pattern is widely use in for different file extensive checking You can
just change the end combination (jpg|png|gif|bmp) to come out different file extension checking
that suit your need.
Java Regular Expression Example
Trang 30public class ImageValidator{
* Validate image with regular expression
* @param image image for validation
* @return true valid image, false invalid image
*/
}
Image file that match:
1 “a.jpg”, “a.gif”,”a.png”, “a.bmp”,
2 “ jpg”, “ gif”,” png”, “ bmp”,
3 “a.JPG”, “a.GIF”,”a.PNG”, “a.BMP”,
4 “a.JpG”, “a.GiF”,”a.PnG”, “a.BmP”,
5 “jpg.jpg”, “gif.gif”,”png.png”, “bmp.bmp”
Image that doesn’t match:
1 “.jpg”, “.gif”,”.png”,”.bmp” – image file name is required
2 ” jpg”, ” gif”,” png”,” bmp” – White space is not allow in first character
3 “a.txt”, “a.exe”,”a.”,”a.mp3″ – Only image file extension is allow
3 “jpg”, “gif”,”png”,”bmp” – image file extension is required
Unit Test – ImageValidator
Trang 31private ImageValidator imageValidator;
@BeforeClass
@DataProvider
"a.jpg", "a.gif","a.png", "a.bmp", " jpg", " gif"," png", " bmp", "a.JPG", "a.GIF","a.PNG", "a.BMP", "a.JpG", "a.GiF","a.PnG", "a.BmP", "jpg.jpg", "gif.gif","png.png", "bmp.bmp"
{new String[]
".jpg", ".gif",".png",".bmp", " jpg", " gif"," png"," bmp", "a.txt", "a.exe","a.","a.mp3",
boolean valid = imageValidator.validate(temp)
System.out.println("Image is valid : " temp + " , "
boolean valid = imageValidator.validate(temp)
System.out.println("Image is valid : " temp + " , "
Trang 32}
Unit Test – Result
Image is valid : a.jpg , true
Image is valid : a.gif , true
Image is valid : a.png , true
Image is valid : a.bmp , true
Image is valid : jpg , true
Image is valid : gif , true
Image is valid : png , true
Image is valid : bmp , true
Image is valid : a.JPG , true
Image is valid : a.GIF , true
Image is valid : a.PNG , true
Image is valid : a.BMP , true
Image is valid : a.JpG , true
Image is valid : a.GiF , true
Image is valid : a.PnG , true
Image is valid : a.BmP , true
Image is valid : jpg.jpg , true
Image is valid : gif.gif , true
Image is valid : png.png , true
Image is valid : bmp.bmp , true
Image is valid : jpg , false
Image is valid : gif , false
Image is valid : png , false
Image is valid : bmp , false
Image is valid : jpg , false
Image is valid : gif , false
Image is valid : png , false
Image is valid : bmp , false
Image is valid : a.txt , false
Image is valid : a.exe , false
Image is valid : a , false
Image is valid : a.mp3 , false
Image is valid : jpg , false
Image is valid : gif , false
Image is valid : png , false
Image is valid : bmp , false
PASSED: ValidImageTest([Ljava.lang.String;@1d4c61c)PASSED: InValidImageTest([Ljava.lang.String;@116471f)
Trang 336.How to validator IP address with regular expression.
Whole combination means, digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255″.
"^([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])$";
Trang 34public IpAddressValidator(){
pattern=Pattern.compile( IP_ADDRESS_PATTERN);}
matcher=pattern.matcher(ipadress);
ipAddressValidator=new IpAddressValidator();}
"1.1.1.1","255.255.255.255", "192.168.1.1","10.10.1.1",
"132.254.111.10","26.10.2.10",
"127.0.0.1"
};
}
"10.10.10","10.10", "10","a.a.a.a",
Trang 35return ipAddressValidator;}
ipAddressValidator) {
this.ipAddressValidator = ipAddressValidator;
}
TestIpAddressValidator test=new TestIpAddressValidator();
Trang 36Whole combination means, digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255″.
1 Java Regular Expression Example
IPAddressValidator.java
Trang 37import java.util.regex.Pattern;
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address */
4 “a.a.a.a” – only digit has allowed
5 “10.0.0.a” – only digit has allowed
6 “10.10.10.256″ – digit must between [0-255]
7 “222.222.2.999″ – digit must between [0-255]
8 “999.10.10.20″ – digit must between [0-255]
9 “2222.22.22.22″ – digit must between [0-255]
10 “22.2222.22.2″ – digit must between [0-255]
4 Unit Test
IPAddressValidatorTest.java
Trang 38@DataProvider
{"26.10.2.10"}
}}
@DataProvider
boolean valid = ipAddressValidator.validate(ip)
System.out.println("IPAddress is valid : " ip + " , "
boolean valid = ipAddressValidator.validate(ip)
System.out.println("IPAddress is valid : " ip + " , "
Trang 39Assert.assertEquals(false, valid)}
}
5 Unit Test – Result
IPAddress is valid : 1.1.1.1 , true
IPAddress is valid : 255.255.255.255 , true
IPAddress is valid : 192.168.1.1 , true
IPAddress is valid : 10.10.1.1 , true
IPAddress is valid : 132.254.111.10 , true
IPAddress is valid : 26.10.2.10 , true
IPAddress is valid : 127.0.0.1 , true
IPAddress is valid : 10.10.10 , false
IPAddress is valid : 10.10 , false
IPAddress is valid : 10 , false
IPAddress is valid : a.a.a.a , false
IPAddress is valid : 10.0.0.a , false
IPAddress is valid : 10.10.10.256 , false
IPAddress is valid : 222.222.2.999 , false
IPAddress is valid : 999.10.10.20 , false
IPAddress is valid : 2222.22.22.22 , false
IPAddress is valid : 22.2222.22.2 , false
Trang 40# or
(\\s)?(?i)(am|pm)";
pattern=Pattern.compile( TIME_PATTERN);
}
matcher=pattern.matcher(time);
}
}
TestTime12HoursValidator.java
time12HoursValidator=new Time12HoursValidator();