You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let's learn about quantifiers in regular expressions.
11
11
@@ -25,6 +25,8 @@ const regex = /^\d{4}$/;
25
25
26
26
Notice how our quantifier contains only the number `4`. This syntax means "match the previous character exactly four times". Let's see how that behaves:
The pattern only matches the string with exactly four digits, because we have used the anchors and our quantifier only allows exactly four digits. But maybe the identification code only needs to be a minimum of four digits.
38
42
39
43
To allow for four or more digits, add a comma after the number in your quantifier:
@@ -44,6 +48,8 @@ const regex = /^\d{4,}$/;
44
48
45
49
Now, our syntax allows the pattern to match four or more digits. Let's test it:
A seven-digit identifier is rather long. These identifiers should have a maximum of 6 digits, and a minimum of 4 digits. To achieve this, you can add a second number to your quantifier after the comma:
57
65
58
66
```js
@@ -61,6 +69,8 @@ const regex = /^\d{4,6}$/;
61
69
62
70
And now our pattern no longer matches the seven-digit identifier, because it is greater than our six-digit maximum.
Note that you cannot use this syntax to set a maximum alone – you must always set a minimum. But if you set the minimum to `1`, you can effectively achieve the same result.
74
86
75
87
We've received updated requirements from our users. Identifiers can now optionally start with a letter. We already know the character class for this, so let's add that to our regular expression:
76
88
77
89
```js
78
-
constregex=/^[a-zA-z]\d{4,6}$/;
90
+
constregex=/^[a-zA-Z]\d{4,6}$/;
79
91
```
80
92
81
93
But now we mandate the presence of a letter. How can we make it optional?
Our pattern now allows for a single optional letter, followed by four to six digits.
108
124
109
125
Unfortunately, we've just realized we read the requirements wrong. We need to allow for any number of letters before the numbers. We can use our quantifier with a `0` minimum and no defined maximum:
But our pattern is getting long again. Thankfully, there's another short-hand for "match the previous character zero or more times" – the asterisk (`*`) symbol. Let's replace our quantifier with that in the pattern, and test it:
Now we successfully match any identifier with zero or more letters followed by four to six numbers. But it turns out this is crashing our system – we actually have to require at least one letter.
128
148
129
149
Again, we could use a quantifier with a minimum of one and no defined maximum, or we could use yet another special syntax – the plus (`+`) symbol:
0 commit comments