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 exerciseMore exercises in Groups and alternation
- Alternation: cat, dog or birdFree
- Alternation with anchorsFree
- Capture a standalone yearFree
- Group without capturingFree
- Backreference: doubled wordsFree
- Matching quote marksFree
- Optional group: phone extensionFree
- Repeated group: dotted numbersFree
- Alternation inside a groupFree
- Grouped alternatives: Mr, Mrs, Ms, DrFree
- Alternation precedence: image file namesFree
- Backreference: a doubled letterFree
- Two captures: major and minor versionFree
- Nested groups: a time and its hourFree