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 advanced

How to Use Backreferences in Regex?

Backreferences allow you to refer to previously matched groups, making it easier to validate repeated patterns or matching tags.

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

"Use backreferences to match repeated words or ensure opening and closing tags match"

Regex
(\b\w+\b)\s+\1|<([a-z]+)>(.*?)</\2>

This regex pattern matches repeated words or ensures that opening and closing HTML tags are the same.

Step-by-step breakdown

  1. The first part (\b\w+\b) captures a word and stores it as group 1.
  2. The \s+ matches one or more whitespace characters following the first word.
  3. \1 refers back to the first captured group, ensuring the same word is matched again.
  4. The second part <([a-z]+)> captures an opening HTML tag and stores it as group 2.
  5. The (.*?) captures any content inside the tags, and </\2> ensures the closing tag matches the opening tag.

Edge cases & warnings

  • Matching case-sensitive words may fail if the case differs.
  • Nested tags might not be correctly matched with this pattern.
  • Words separated by punctuation will not be recognized as repeated.
  • Empty strings may cause unexpected matches.
  • Incorrectly formatted tags will not match.

Examples

Prompt

"hello hello"

Regex
Match found: 'hello'
Prompt

"<div>content</div>"

Regex
Match found: '<div>' and '</div>'

Frequently asked questions

What are backreferences in regex?

Backreferences allow you to refer to a previously captured group in the same regex.

Can backreferences match different cases?

No, backreferences are case-sensitive by default.

How do I match nested tags?

Backreferences alone cannot match nested tags; consider using a more complex regex or a parser.

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.