正则表达式匹配具有相同长度的两个不同组

时间:2017-06-15 18:32:39

标签: regex regex-group

我想构建一个匹配两个组的正则表达式,第二个组由一个字符组成,重复次数与第一个组中的字符数相同。像^(\w+) (x{length of \1})这样的内容,例如,hello xxxxxfoo xxx会匹配,但hello xxxxyfoo xxy则不匹配。这可能吗?

此处的目标是匹配reStructuredText样式列表中的缩进,其中列表项中的第二行应缩进以匹配第一行中文本的开头,不包括可变长度数字列表标记。例如,

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 个答案:

答案 0 :(得分:1)

如果

,你可以这样做
  1. 你的正则表达式引擎支持条件模式和
  2. 你愿意接受重复次数的固定上限。
  3. 在这种情况下,你可以这样做:

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

    此示例将匹配长度为5。

相关问题