Update我猜你可能会采用一些荒谬的 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 来完成regex module.
需要用到递归。
这样做是因为它实际上只是嵌套的分隔符。
1
1
1
2
2
2
1(?>[^12]++|(?R))*2
https://regex101.com/r/4Nxtvl/1 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
To 不允许内部内容 use 1(?>(?R))*2
https://regex101.com/r/mSUIp0/1 https://regex101.com/r/mSUIp0/1
要添加边界条件,请将递归包含到组中,
然后用边界结构包围它。
(?<!\d)(1(?>[^12]++|(?1))*2)(?!\d)
https://regex101.com/r/SSr1zV/1 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
To 不允许内部内容 use (?<!\d)(1(?>(?1))*2)(?!\d)
https://regex101.com/r/VI6w0Y/1 https://regex101.com/r/VI6w0Y/1