gpt4 book ai didi

javascript - 获取两个字符串之间最长的完美匹配javascript

转载 作者:行者123 更新时间:2023-12-04 08:47:42 25 4
gpt4 key购买 nike

这是我们的字符串:

const a = "your majesty they are ready";
const b = "your highness they are ready";
我想得到一个包含两个字符串之间最长精确匹配的数组。
所以对于第一个字符串,我们会得到:
[ ["your"], ["they are ready"] ]
不是 这个得到最短匹配的结果:
[ ["your"], ["they"], ["are"], ["ready"] ]
获得单词匹配对我来说是一件容易的事。但我需要一个人来找出一个合适的解决方案,以获得尽可能长的精确匹配......
顺便说一下,我正在使用此函数来检查完全匹配:
// exactMatch("I was sent","sent") returns true And exactMatch("I was sentt","sent") returns false
function exactMatch(ref,compare) {
return new RegExp("\\b" + ref + "\\b").test(compare);
}
备注 :我不想要最长的匹配...我想要所有可能的最长匹配。

最佳答案

像这样的东西:

function exactMatch(a, b) {
a = a.split(' ');
b = b.split(' ');
let s = [];
let out = [];
let x = a.map(x => b.includes(x) ? x : null);
x.forEach((v) => {
if (v == null) {
out.push(s);
s = [];
} else {
s.push(v);
}
});
out.push(s);
out = out.map(x => x.join(' ')).filter(x => x);
return out;
}
let a = "your majesty they are ready";
let b = "your highness they are ready";
let c = exactMatch(a, b);
console.log(c);

a = "your majesty they are ready, but this is another test";
b = "your highness they are ready, yet this is another test";
c = exactMatch(a, b);
console.log(c);

a = "hello your majesty they are ready, but this is another test";
b = "hi your highness they are ready, yet this is another test";
c = exactMatch(a, b);
console.log(c);

a = "hello your majesty they are ready, but this is another test made";
b = "hi your highness they are ready, yet this is another test completed";
c = exactMatch(a, b);
console.log(c);

关于javascript - 获取两个字符串之间最长的完美匹配javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64225199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com