我不想在字符串 ["kkkabczzz", "shdirabckai"] 中找到“abc”
不是那样的。
但更大的模式是这样的:
如果我必须__,那么我会___。
[“如果我必须做,那么我会做对。”,“即使我必须做,没有 jack 我也不会做。”,“......如果我必须做,我不会……”]
我想发现大型数组或字符串数据库中的模式。假设浏览整本书的内容。
有没有办法找到这样的模式?
我可以使用 JavaScript、Python、PHP。
最佳答案
以下内容可以作为起点:
RegExp rx=/(\b\w+(\s+\w+\b)+)(?=.+\1)+/g
寻找小的(多词)模式在文本中至少出现两次。
通过在 (\s+\w+\b)
之后使用重复量词 +
(即将其更改为类似 {2}
) 您可以将您的单词模式限制为任意数量的单词(在上述情况下为 3:原始 + 2 次重复),您将得到不同的结果。
(?=.+\1)+
是一种前瞻模式,不会消耗字符串的任何匹配部分,因此剩余的匹配尝试还有“更多字符串”在 while
循环中。
const str="If I have to do it, then I will do it right. Even if I have to make it, I will not make it without Jack. If I have to do, I will not."
const rx=/(\b\w+(\s+\w+\b)+)(?=.+\1)+/g, r={};
let t;
while (t=rx.exec(str)) r[t[1]]=(rx.lastIndex+=1-t[1].length);
const res=Object.keys(r).map(p=>
[p,[...str.matchAll(p)].length]).sort((a,b)=>b[1]-a[1]||b[0].localeCompare(a[0]));
// list all repeated patterns and their occurrence counts,
// ordered by occurrence count and alphabet:
console.log(res);
我通过将所有匹配项收集为对象 (r
) 中的键来稍微扩展我的代码段。最后,我使用 Object.keys(r).sort()
按字母顺序列出了该对象的所有键。
在 while
循环中,我还重置了 rx.lastIndex
属性,以便在找到的最后一个模式开始后立即开始搜索下一个模式: rx.lastIndex+=1-t[1].length
.
关于substring - 如何在数千个字符串中找到共同的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72591638/