首页 > 解决方案 > 检查文本是否是系列的子集

问题描述

我想根据一个系列检查一个字符串(关于顺序)
- 请参阅下面的另一种方法(字符串解决方案)

正则表达式解决方案(潜在)

r = /[(qw|az)ert(y|z)uiop(é|å|ü)]{5}/g
str = "ertyu"
str2 = "rtrrr"

r.test(str)  // true 
r.test(str2) // true

str2 应该返回 false 因为它不遵守顺序,但由于正则表达式被包装在数组中,我认为这种方法从一开始就是错误的。

字符串解决方案

arr = [
  "qwertyuiopé",
  "qwertyuiopå",
  "qwertyuiopü",
  "qwertzuiopé",
  "qwertzuiopå",
  "qwertzuiopü",
  "azertyuiopé",
  "azertyuiopå",
  "azertyuiopü",
  "azertzuiopé",
  "azertzuiopå",
  "azertzuiopü",
]
str = "ertyu"
str2 = "yrwqp"

function test(s) {
  for (const a of arr) {
    if (a.indexOf(str) >= 0) return true
  }
  return false
}

test(str)  // true
test(str2) // false

字符串版本有效,但它又丑又大

正则表达式有没有办法让它工作?

标签: javascriptregex

解决方案


最后,我认为我想要实现的目标是不可能的,我最终得到了一系列不同系列(键盘琐碎系列)和一个检查密码是否是系列序列的函数

const trivialseries = [
  // swedish, german, french, english, spanish, italian - keyboard
  "1234567890",
  "qwertyuiopå", // se|en
  "asdfghjklöä",
  "zxcvbnm",
  "qwertzuiopü", // de
  "yxcvbnm",
  "azertyuiop", // fe
  "qsdfghjklmù",
  "wxcvbn",
  "asdfghjklñ", // sp
  "qwertyuiopé", // it
  "asdfghjklòàù",
];
const MAX = 5;

function subsequence(serie, str) {
  for (let i = 0; i < str.length - MAX + 1; i++) {
    const index = serie.indexOf(str[i]);

    if (index >= 0) {
      let found = 1;
      for (let j = i + 1; j < str.length; j++) {
        if (serie[index + found] === str[j]) found++;
        else break;
        if (found === MAX) return true;
      }
    }
  }

  return false;
}

function isTrivial(password) {
  for (let ts of trivialseries) {
    if (subsequence(ts, password)) return true;
    const reverse = ts.split("").reverse().join("");
    if (subsequence(reverse, password)) return true;
  }

  return false;
}

console.log(isTrivial("e927ncsmnbvcdkeloD€%s567jhdoewpm")); // true "mnbvc" is reverse form of "cvbnm"

推荐阅读