Regexdrill

Level 2: Groups and alternation Exercise 23 of 70 Free

Alternation precedence: image file names

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

The whole line must match. Match a file name made of word characters, a period and one of the lowercase extensions jpg, jpeg, png or gif.

What this exercise teaches

\w+\.(?:jpg|jpeg|png|gif) puts the alternatives in a group, so each one is reached only after the name and the period. The jpg branch is tried before jpeg, but photo.jpeg still passes: when jpg leaves text unmatched, the engine backtracks and tries the next alternative.

A hint if you get stuck

Without a group, \w+\.jpg|png means (\w+\.jpg) or (png). Group the extensions so the name and the period apply to all of them.

Try it now, free, no account needed

Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro adds timed mode and the certificate.

Open this exercise

More exercises in Groups and alternation