首页 > 解决方案 > 正则表达式获取捕获组的大小

问题描述

是否可以编写一个正则表达式,我可以稍后在同一个正则表达式中以某种方式引用“第一个捕获组的长度”?我在这里想要实现的是捕获 ' 的连续出现,1然后是 ' 的连续出现的确切数量2

我想要类似的东西

r"(1*)(2{length(\1)})" # where `length(\1)` should give me the length of capture group 1

应该匹配

1122 # two 1's followed by two 2's
111222 # three 1's followed by three 2's
121122111222 # should match `12` and `1122` and `111222` separately

不应该匹配

122 # there are two 2's following one 1
112 # there are two 1's but only one 2
11222 # same as above but with different occurrences
11122 # same as above but with different occurrences

标签: pythonregexre

解决方案


更新我想您可以使用一些无法正常工作的荒谬 Java 前瞻递归模拟,
或者您可以使用 Python 来完成它?

>>> import regex
>>> rx_1_2 = r"(?m)^(1(?>(?1))*2)$"
>>>
>>> input = '''
... 111222222
... 11222234
... 1111222
... 111222
... 1122
... 12
... '''
>>> res = regex.findall( rx_1_2, input )
>>> print( res )
['111222', '1122', '12']

这个问题被标记为
使用前瞻的 Java 模拟递归的副本,对于通过将其标记为副本来覆盖这个问题的人来说,这是一个非常糟糕的判断。只是判断力差...


可以使用 python正则表达式模块来完成。
需要使用递归。
这样做是因为它实际上只是嵌套的分隔符。

1
  1
    1
    2
  2
2

1(?>[^12]++|(?R))*2

https://regex101.com/r/4Nxtvl/1

                         # Recursion 
 1                       # 1
 (?>                     # Atomic group
      [^12]++                 # Possesive, not 1 or 2
   |                        # or,
      (?R)                    # Recurse the regex
 )*                      # End cluster, do 0 to many times
 2                       # 2

不允许内部内容使用1(?>(?R))*2 https://regex101.com/r/mSUIp0/1


要添加边界条件,请包含对组的递归,
然后用边界构造包围它。

(?<!\d)(1(?>[^12]++|(?1))*2)(?!\d)

https://regex101.com/r/SSr1zV/1

 (?<! \d )               # Not a digit behind
 (                       # (1 start), Recursion code group
    1                       # 1
    (?>                     # Atomic group
       [^12]++                 # Possesive, not 1 or 2
     |                        # or,
       (?1)                    # Recurse the regex group 1
    )*                      # End cluster, do 0 to many times
    2                       # 2
 )                       # (1 end)
 (?! \d )                # Not a digit ahead

不允许内部内容使用 (?<!\d)(1(?>(?1))*2)(?!\d) https://regex101.com/r/VI6w0Y/1


推荐阅读