如何比较字符串和检查阈值相等?

问题描述 投票:3回答:2

我必须比较字符串,我想测试他们的字符是否与大多数a元素不同,例如:

// for a = 2 comparing all strings with str1
var str1 = 'qwerty'; // should return true
var str2 = 'qwerty'; // should return true
var str3 = 'qw1rty'; // should return true
var str4 = '1wery1'; // should return true
var str5 = 'q1e11y'; // should return false

为了做到这一点,我创建了一个有效的功能,但我想知道我是否可以使用regex。我的实际功能:

function test(str1, str2, limit) {
  const occ = str1.split('').reduce((acc, char, idx) => str2[idx] == char ? ++acc : acc, 0);
  return str1.length - occ <= limit;
}

// for a = 2 comparing all strings with str1
var str1 = 'qwerty'; // should return true
var str2 = 'qwerty'; // should return true
var str3 = 'qwert1'; // should return true
var str4 = 'qwer11'; // should return true
var str5 = 'qwe111'; // should return false

console.log(test(str1, str1, 2)) // true
console.log(test(str1, str2, 2)) // true
console.log(test(str1, str3, 2)) // true
console.log(test(str1, str4, 2)) // true
console.log(test(str1, str5, 2)) // false

有没有办法用regex实现这个目标?

javascript regex
2个回答
3
投票

您可以使用正则表达式匹配当前正确的字母。如果没有匹配,则捕获当前字符。然后计算捕获的字符数并进行比较。对于单词qwerty,这将是正则表达式:

(?:q|(.))(?:w|(.))(?:e|(.))(?:r|(.))(?:t|(.))(?:y|(.))

JS代码:

function testDistance(str1, str2, limit) {
    reStr = '(?:' + str1.split('').join('|(.))(?:') + '|(.))';
    return (new RegExp(reStr)).exec(str2).filter(Boolean).length - 1 <= limit;
}

var str1 = 'qwerty'; // should return true
var str2 = 'qwerty'; // should return true
var str3 = 'qwert1'; // should return true
var str4 = 'qwer11'; // should return true
var str5 = 'qwe111'; // should return false

console.log(testDistance(str1, str1, 2)) // true
console.log(testDistance(str1, str2, 2)) // true
console.log(testDistance(str1, str3, 2)) // true
console.log(testDistance(str1, str4, 2)) // true
console.log(testDistance(str1, str5, 2)) // false

1
投票

是的,您可以使用以下代码从给定的字符串创建正则表达式。然后它计算正则表达式与另一个字符串的匹配,以确定距离:

function test(str1, str2, limit) {
  // First: Create a regexp from the given input string:
  // "qwerty" -> ["q","w","e","r","t","y"]
  //          -> ["(q)?","(w)?","(e)?","(r)?","(t)?","(y)?"] 
  //          -> (q)?(w)?(e)?(r)?(t)?(y)?
  let regexp = new RegExp(str1.split('').map(e => `(${e})?`).join(''));

  let match = str2.match(regexp);
  if(!match) {
    return false;
  }
  // Now calculate the matches, which did not fulfill the question mark regexp brackets.
  let notEmpty = function(e) { return e; };

  return str2.length - (match.filter(notEmpty).length - 1) <= limit;
}
© www.soinside.com 2019 - 2024. All rights reserved.