问题
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.
回答1:
You can do it if
- your regex engine supports conditional patterns and
- 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.
来源:https://stackoverflow.com/questions/44574551/regex-to-match-two-different-groups-with-the-same-length