clwainwright
clwainwright

Reputation: 1704

regex to match two different groups with the same length

I would like to construct a regex that matches two groups, with the second group consisting of a single character repeated the same number of times as the number of characters in the first group. Something like ^(\w+) (x{length of \1}) so, for example, hello xxxxx and foo xxx would match, but hello xxxxy and foo xxy would not. Is this possible?

The goal here is to match indentation in reStructuredText-style lists, where the second line in a list item should be indented to match the start of the text in the first line, excluding the variable-length numerical list marker. For example,

1. If the number is small,
   subsequent lines are typically
   indented three spaces.
2.  Although if the first line has
    multiple leading spaces then
    subsequent lines should reflect that.
11. And when the number starts to get
    bigger the indent will necessarily
    be bigger too.

Upvotes: 3

Views: 1898

Answers (1)

melpomene
melpomene

Reputation: 85767

You can do it if

  1. your regex engine supports conditional patterns and
  2. you're willing to accept a fixed upper bound on the number of repetitions.

In that case you can do something like this:

^(\w)?(\w)?(\w)?(\w)?(\w)? (?(1)x)(?(2)x)(?(3)x)(?(4)x)(?(5)x)

This example will match up to a length of 5.

Upvotes: 4

Related Questions