Regexdrill

Level 2: Groups and alternation Exercise 19 of 52 Pro

Alternation inside a group

A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.

The task

Find a number followed by a unit, with or without one space between them, and capture the unit in group 1. Units are kg, g, lb and oz, and the unit must end the word.

What this exercise teaches

\d+ ?(kg|g|lb|oz)\b captures the unit and refuses one that runs into more letters.

A hint if you get stuck

Group the units with alternation. End with \b so that the g in gallons does not count.

This exercise is part of Pro

Pro unlocks all 52 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Groups and alternation