How to write RegEx
If you are a developer then at least once in your career you face a situation where you have to write validation for the email field or password field or mobile number.
It’s a headache for everyone to write Regex and the maximum developer does search on google regex for the password field. It’s easy right ??
But as a developer, you should know how to write RegEx and what is the meaning of every symbol we use. It’s better to understand once rather than googling every time. Right ?? So let’s understand each section thoroughly in this blog.
[abc] : It means a , b or c
[^abc]: It means any character except a, b, c
[a-z]: a to z
[A-Z]: A to Z
[a-z A-Z]: a to z , A to Z
[0–9]: 0 to 9
[ ]? : occurs 0 or 1 times
[ ]+ : Occures 1 or More times
[ ]* : Occurs 0 or more times
[ ]{n} : Occurs n times
[ ]{n, } : Occurs n or more times
[ ] {y,z}: Occurs at least y times but less than or equal to z times.
Now let’s discuss meta characters
Meta characters are mostly short form.
\d : [0–9]
\D: [^0–9]
\w: [a-z A-Z_0–9]
\W: [^\w]
Now let’s take some example and implement it. That will more understandable.
Q1. Check mobile numbers that start with 8 or 9 and the total digits will be 10.
[8 9][0–9]{9} this means [8 9] = 1st digit 8 or 9 then [0–9]{9} means rest 9 numbers are any digit from 0 to 9.
Q2. The first character should be upper case, it should contain lower case alphabets, and only one digit is allowed in between.
[A-Z][a-z]*[0–9][a-z]* This means [A-Z] = 1st character should uppercase. [a-z]*[0–9][a-z]* means lower case n number of times and only one digit in between them.
Q3. Email Id [ Example: baishalypradhan03@gmail.com ]
[a-zA-Z0–9_\-\_\.]+[@][a-z]+[\.][a-z]{2 3}
here if I consider my email id then it container some alphabets then @ and then some lowercase alphabets and then a . symbol and then 3 lowercase alphabet.
So for 1st part alphabet, we wrote [a-zA-Z0–9_\-\_\.]+ which means it should contain a-z or A-Z or 0–9 and maybe be underscored (_), hyphen(-), or maybe a dot( . ). and It occurs 1 or more time so we add + add the end.
Then @ symbol and again some lowercase alphabets [ i.e. gmail ] so we wrote [a-z]+ and a + symbol because it also occurs 1 or more time.
Then comes our dot [ . ]symbol after gmail so we wrote [\.]
And finally, in the end, we wrote come or in or co. So we wrote [a-z]{2 3} this means a-z Occurs at least 2 times but less than or equal to 3 times.
Thanks for your time. 😀
Hope it is clear now. If I forgot something then please let me know in the comment section.