Regular Expression template for web development
Bài đăng này đã không được cập nhật trong 3 năm
What is regular expression?
A regular expression is a special text string for describing a search pattern, mainly for use in pattern matching with strings, or string matching.
Regex quick reference
Sample | Definition |
---|---|
[abc] |
A single character of: a, b, or c |
[^abc] |
Any single character except: a, b, or c |
[a-z] |
Any single character in the range a-z |
[a-zA-Z] |
Any single character in the range a-z or A-Z |
^ |
Start of line |
$ |
End of line |
\A |
Start of string |
\z |
End of string |
. |
Any single character |
\s |
Any whitespace character |
\S |
Any non-whitespace character |
\d |
Any digit |
\D |
Any non-digit |
\w |
Any word character (letter, number, underscore) |
\W |
Any non-word character |
\b |
Any word boundary |
(...) |
Capture everything enclosed |
(a|b) |
a or b |
a? |
Zero or one of a |
a* |
Zero or more of a |
a+ |
One or more of a |
a{3} |
Exactly 3 of a |
a{3,} |
3 or more of a |
a{3,6} |
Between 3 and 6 of a |
options: |
The Common regular expression template
1. Email
/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
- Match email:
- user@email.com
- mkyong.100@mkyong.com.ss
- 123-user@email.com
- jame-007@yahoo-test.com
- Don't match email:
- user@email.1com
- user@email.
- user@email
- useremail.com
2. Phone number
/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/
- Match Phone number
- 123-456-7890
- (123) 456-7890
- 123 456 7890
- 123.456.7890
- +91 (123) 456-7890
3. HTTP Url
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
- Valid URL
- Invalid URL
- https://viblo
- ttps://viblo.asia
- //viblo.asia
4. IP Address
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
- Valid IP
- 192.168.100.1
- 127.0.0.1
- 0.0.0.0
- Invalid IP
- 256.123.123.1
- 192.168.122.
- 192.168.122
5. Username
/^[a-z0-9_-]{3,32}$/i
- Valid username
- Jame007
- user_Name
- like-you
- Invalid username
- a hacker
- me+
- you&I
6. Password
/^([a-zA-Z0-9@*#]{6,15})$/
- Valid password
- password
- password123
- P@ssw0rd
- Invalid password
- Hello
- My password
- no-one-can-guess-my-passord
7. File Extension
([^\s]+(\.(?i)(jpg|png|gif|bmp))$)
- Match file
- picture.jpg
- picture123.png
- image.gif
- Don't match file
- picture.txt
- cat-photo.
- no-image
8. Time Format
/([01]?[0-9]|2[0-3]):[0-5][0-9]/
- Match Time
- 00:00
- 22:00
- 9:00
- Don't match time
- 00:0
- 24:00
- 12:65
9. Date Format (dd/mm/yyyy, dd-mm-yyyy)
/^(\d\d)[-\/](\d\d)[-\/](\d\d(?:\d\d)?)$/
- Match date
- 11-02-2015
- 11/02/2015
- Date don't match
- 12-Feb-1222
- 2-1-15
Try online: http://rubular.com/
All rights reserved