/U (Ungreedy)
What is /U (Ungreedy)?
/U (Ungreedy): Swaps the default greediness of quantifiers: * and + become lazy by default, and adding ? after them makes them greedy again. The U modifier in PHP swaps greediness. Normally .* grabs as much as it can and .*? takes as little as possible. With U, .* becomes lazy and .*? becomes greedy.
Frequently asked questions about /U (Ungreedy)
How is /U (Ungreedy) used in practice?
It can make a pattern full of lazy matches look tidier. The downside is that anyone reading it has to notice the flag at the end, or they will understand every quantifier the wrong way round.
What should you keep in mind with /U (Ungreedy)?
Most developers know the standard meaning of ? after a quantifier. Writing .*? explicitly is a little longer, but it reads the same in PHP, JavaScript, Python and every regex tester. Prefer that over U in shared code. If you do use the flag, keep the pattern short and add a comment, because a misunderstanding here leads to matches that are too long or too short.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |