Regular expressions that programmers often use

Tram Ho

As in the previous article, I introduced some basic regex concepts. In this article I will introduce a few cases of using regex in practice.

1. Check Email

^[az][a-z0-9_.]{5,32}@[a-z0-9]{2,}(.[a-z0-9]{2,4}){1,2}$

Checking for an email for accuracy is extremely important in programming to authenticate users’ accounts.

2. Password strength

^(?=.*[AZ].*[AZ])(?=.*[ [email protected] #$&*])(?=.*[0-9].*[0-9])(?=.*[az].*[az].*[az]).{8}$

Similar to email, the strength of passwords is also quite important in protecting user accounts

3. Validating IPv4 addresses

/b(?:(?: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]?)b/

Authentication IP address is used to determine the user’s Internet access address

4. Authentication of IPv6 addresses

(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))

In addition to IPv4, there is now another IP that is also commonly used as IPv6.

5. Check valid domain name

/https?://(?:[-w]+.)?([-w]+).w+(?:.w+)?/?.*/i

Checking a valid domain name is also very important in web programming

6. Verify phone number

^+?d{1,3}?[- .]?(?(?:d{2,3}))?[- .]?ddd[- .]?dddd$

Authentication of phone numbers is also extremely important in authenticating user information

7. Get the image source

< *[img][^>]*[src] *= *["']{0,1}([^"' >]*)

When you crawl the data but only want to get the image source, you can use the above expression

8. Credit card number

^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35d{3})d{11})$

Authentication of credit card numbers is also extremely important to protect the server

9. Facebook personal page URL

/(?:http://)?(?:www.)?facebook.com/(?:(?:w)*#!/)?(?:pages/)?(?:[w-]*/)*([w-]*)/

For facebook engines: 3

10. Validate dates in DD / MM / YYYY format

^(?:(?:31(/|-|.)(?:0?[13578]|1[02]))1|(?:(?:29|30)(/|-|.)(?:0?[1,3-9]|1[0-2])2))(?:(?:1[6-9]|[2-9]d)?d{2})$|^(?:29(/|-|.)0?23(?:(?:(?:1[6-9]|[2-9]d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1d|2[0-8])(/|-|.)(?:(?:0?[1-9])|(?:1[0-2]))4(?:(?:1[6-9]|[2-9]d)?d{2})$

Extract the date from a paragraph, as well as validate the data transmitted from the user.

Share the news now

Source : Viblo