../courses.php
RegEx
REGEX105
3
Control How Many Times Text Can Appear
Quantifiers control whether something appears once, many times, or a specific number of times.
What does repetition mean in RegEx?
Repetition means a pattern part can match a certain number of times, such as zero or more, one or more, optional, or an exact count.
RegEx is often used when text length can change.
A name may have many letters. A number may have several digits.
Quantifiers tell RegEx how many times the previous part may repeat.
Common quantifiers include *, +, ?, and {3}.
Repetition is powerful, but careless repetition can match too much.
Matching repeated digits
console.log(/[0-9]+/.test("Room 204")); // true
console.log(/[0-9]+/.test("Room ABC")); // false
console.log(/colou?r/.test("color")); // true
console.log(/colou?r/.test("colour")); // true
console.log(/^[0-9]{3}$/.test("123")); // true
console.log(/^[0-9]{3}$/.test("12")); // false
+ means one or more of the previous part.
? means optional: zero or one.
{3} means exactly three times.
[0-9]+ means one or more digits.
The quantifier controls the part directly before it.
Length
Repetition handles text that can be longer or shorter.
Validation
Exact counts help check codes and numbers.
Optional text
Question marks handle small variations.
Risk
Loose repetition can match more than intended.
Too much
Controlled repeat
Ask ChatGPT: "Does this quantifier repeat only the part I intend, and have I tested short and long examples?"
Write a pattern that matches one or more digits.
Write a pattern that matches exactly three digits.
Use ? to make one letter optional.
Explain what + means.
Explain why .* can be dangerous.
Thinking + means one character instead of one or more.
Forgetting that the quantifier affects the previous part.
Using * when at least one character is required.
Using .* too early.
Not testing minimum and maximum cases.
Use quantifiers to control how many times a pattern part may repeat.
Login - Jit4All
Login
Welcome back to Jit4All