Regexdrill

Level 2: Groups and alternation Exercise 22 of 88 Free

Backreference: matching HTML tags

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 an opening tag, any text and a closing tag with the same name, like <b>bold</b>. Tag names are word characters with no attributes, and the text can be empty.

What this exercise teaches

<(\w+)>.*</\1> captures the name of the opening tag and \1 repeats exactly that text in the closing tag. Writing \w+ twice would accept <b>bold</i>, because each \w+ matches on its own.

A hint if you get stuck

Capture the tag name in a group, then use \1 in the closing tag to demand the same name again.

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. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Groups and alternation