Look ahead (?=)
exp1(?=exp2)
Find exp1 followed by exp2
regular expression | string | Match results |
---|---|---|
abc(?=123) | abc123 | abc |
abc(?=123) | kabc1234 | abc |
abc(?=123) | abc12 | Mismatch |
abc(?=123) | abcc123 | Mismatch |
Note: (?=) represents the end, do not mix it with $. For example, ^abc(?=123)$ cannot match abc123, ^abc(?=123) can match abc123
Negative lookahead(?!)
exp1(?!exp2)
Find exp1 that is not followed by exp2
regular expression | string | Match results |
---|---|---|
abc(?!123) | abc123 | Mismatch |
abc(?!123) | abc1233 | Mismatch |
abc(?!123) | abc12 | abc |
abc(?!123) | abcc123 | abc |
Looking back (?<=)
(?<=exp2)exp1
Find exp1 preceded by exp2
regular expression | string | Match results |
---|---|---|
(?<=abc)123 | abc123 | 123 |
(?<=abc)123 | kabc1234 | 123 |
(?<=abc)123 | abc12 | Mismatch |
(?<=abc)123 | abcc123 | Mismatch |
Negative (?<!)
(?<!exp2)exp1
Find exp1 that is not preceded by exp2
regular expression | string | Match results |
---|---|---|
(?<!abc)123 | abc123 | Mismatch |
(?<!abc)123 | kabc1234 | Mismatch |
(?<!abc)123 | ab1234 | 123 |
(?<!abc)123 | abcc123 | 123 |
Example: Regular expression of password rules, which must contain letters + numbers + special characters (the special characters here are !@#$), with a length of 8-16 characters
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$])[\da-zA-Z!@#$]{8,16}$