DELAPARRA
Index
Color
NL
Category: Regex flags

/U (Ungreedy)

Explained by Updated

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.

Definition source Coders Lingo, CC BY 4.0

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

CategoryRegex flags
Explained by
Updated

More Regex flags terms

All terms starting with a number or symbol

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.