Regular Expression aka RegEx
String, email validation using RegEx in iOS
Reserved / Literal Characters
- [ ] — Square Bracket
- {} — Curly braces
- ( ) — Capturing Parentheses
- | — Pipe Character (OR)
- ^, & — Anchors
Square Bracket [ ]
It represents the possible set of single-character that matches with the given string. For example, k[arthik] matches with ka, kr, kt, kh, ki, kk. The important point is the characters inside the square bracket are case-sensitive. Inside the square bracket, we can add the range of characters too. e.g., [a-z](all small case alphabets), [A-Z](all upper case alphabets), [0–9](all numeric characters), [a-d] small case letters from a to d, [^a-d] small case letters excluding a to d, [a-zA-Z] — only alphabets, [0–9] — only numbers, [a-zA-Z0–9] — alpha-numeric characters only.
Curly braces { }
It represents the min and max number of matches. i.e., {n,m} Between n and m times, {n,} — n or more (min of n), {n} Exactly n times. In the below example, the domain is validated i.e., it should contain a minimum of 2 and a maximum of 3 lower case alphabets. In the second example, only one number is mentioned (i.e., it accepts exactly 10 digit numbers) whereas in the last example only the minimum number is mentioned i.e., it accepts the minimum of 10 digit numbers.
Capturing Parentheses ( )
It is used to group the patterns. In the below example, theDomainRegex “[.](in|com|net)” would match either “.in” or “.com”, “.net”.
Pipe Character | (OR)
It acts as an OR logic. In the above example, the pipeline is used inside the capturing Prarnthesis. i.e., it either matches in or com or net.
Anchors ^, &
^ and & matches at the beginning and end of a line respectively.
Quantifiers (*, +, ?)
- * => zero or more matches
- + =>one or more
- ? => zero or one
The Asterisk(*) and Plus(+) is not mostly used in the string validation but it is mostly used in the String Search.
Validating the Email
Here I’m writing the simple email Regex to validate the email based on the requirements given.
Find it a good read?
Recommend this post (by clicking the 👏 button) so other people can see it too… reach me on LinkedIn Karthikeyan