正则表达式匹配具有相同长度的两个不同组 [英] regex to match two different groups with the same length

查看:42
本文介绍了正则表达式匹配具有相同长度的两个不同组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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. 您的正则表达式引擎支持条件模式和
  2. 您愿意接受重复次数的固定上限.

在这种情况下,您可以执行以下操作:

In that case you can do something like this:

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

此示例最多匹配 5 个长度.

This example will match up to a length of 5.

这篇关于正则表达式匹配具有相同长度的两个不同组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆