We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
Regex intermediate

How to Extract Content Between HTML Tags Non-Greedily?

Using non-greedy matching in regex can help you accurately extract content between HTML tags without capturing too much data.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Extract content between HTML tags using non-greedy matching to avoid over-matching"

Regex
<([^>]+?)>(.*?)</\1>

This regex pattern extracts content between HTML tags using non-greedy matching to prevent over-capturing.

Step-by-step breakdown

  1. The '<([^>]+?)>' part matches the opening HTML tag non-greedily.
  2. The '(.*?)' captures any content between the tags non-greedily.
  3. The '</\1>' matches the corresponding closing tag using backreference.
  4. The '?' after '*' ensures that the match is non-greedy, stopping at the first closing tag.

Edge cases & warnings

  • HTML tags with attributes may complicate matches.
  • Nested HTML tags can lead to unexpected results.
  • Self-closing tags may not return any content.
  • Empty tags will result in no captured content.

Examples

Prompt

"<div>Hello World</div>"

Regex
Hello World
Prompt

"<span>Test <b>Bold</b> Text</span>"

Regex
Test <b>Bold</b> Text

Frequently asked questions

What is non-greedy matching in regex?

Non-greedy matching captures the smallest possible string that satisfies the pattern.

Can this regex handle nested tags?

No, this regex does not handle nested HTML tags correctly.

What if the tags are not well-formed?

The regex may fail to match or return unexpected results with poorly formed tags.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.