regex to match two different groups with the same length

随声附和 提交于 2019-12-14 02:25:22

问题


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

  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.



来源:https://stackoverflow.com/questions/44574551/regex-to-match-two-different-groups-with-the-same-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!