如何使用RE在字符串中查找多个balancedsize匹配项?

2024-04-16 15:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我已将一个问题转化为模式匹配问题,并尝试使用RE来解决它

转换后的问题:给定一个“0/1”字符串,如s = '111100111111100111111001',尝试查找子字符串的3个匹配项:

a '1', followed by arbitrary number of any characters, and then 2 consecutive '1's, and the total size of the match is at least 4.

上述要求可以编码为RE模式:'1.{1,}11'。相反的模式也被接受:'11.{1,}1'。此外,任何2个相邻匹配的间隔应消耗尽可能少的字符

这一切翻译如下代码:

> import re
> s = '111100111111100111111001'
> p = '.*?(1.{1,}11|11.{1,}1).*?(1.{1,}11|11.{1,}1).*?(1.{1,}11|11.{1,}1).*?'
> ret = re.match(p, s)
> ret.groups()

结果是:

> ('1111001111111', '1111', '11001')

这个结果是好的,但在这个意义上是次优的:每场比赛的长度应尽可能平衡

细化结果应为:

('1111001', '1111111', 11111001')

但是我如何使用RE来施加这个约束呢


Tags: andofthe字符串renumberbymatch
1条回答
网友
1楼 · 发布于 2024-04-16 15:00:43

我只能这样想:

&13; 第13部分,;
var input = '111100111111100111111001';

for (var i = input.length; i >= 4; i ) {
  var matches = input.match(new RegExp('.{' + i + '}', 'g'));
  
  var output = matches.filter(x => /^1.+1$/.test(x));
  
  if (output.length === 3) {
    console.log(output)
  }
}
和#13;
和#13;

Starting with 1, ending with 1 and having at least 4 characters

因此,您的示例输入也应该匹配。正如您所看到的,有很多输出可以匹配

1111111
^^^^
1111111
 ^^^^
1111111
  ^^^^
1111111
   ^^^^
1111111
^^^^^
1111111
 ^^^^^
1111111
  ^^^^^
1111111
^^^^^^
1111111
 ^^^^^^
1111111
^^^^^^^

相关问题 更多 >