【发布时间】:2016-05-20 18:36:08
【问题描述】:
我有一个带字符串的数组:
var dict =["johndoe","johnrte","jahnaoi"];
我想创建一个函数(使用正则表达式或其他)来检查缺少字母的“str”是否适合其中一项。缺少的字母用“#”表示。 假设缺少字母的字符串是“j#hn#oe”。 我是这样开始的,但我认为我不会走正确的路。
function Checkword(str) {
// Check were is the #
var indices = [0]
for (var i = 0; i < str.length; i++) {
if (str[i] === "#") indices.push(i);
}
var regexel = "/^";
for (var index = 0; index < indices.length; index++) {
regexel.concat(str.substring(indices[index - 1], indices[index]));
regexel.concat("[a-z]");
}
regexel.concat("$/");
var reg = new Regex(regexel);
for (r = 0; r < dict.length; i++) {
if (reg.test(dict[r]) {
console.log(dict[r]);
}
}
}
Checkword("j#hn#oe");
在这种情况下,它将返回第一项和最后一项。
*** 评论后编辑:
哪个单词应该通过我的测试:
If str is j#hndo#=> dict[0], dict[2].
If str is j####### => dict[0], dict[1], dict[2];
IF str is Jonh#oe=> dict[0]
if str is a#ze#ts=> nothing.
【问题讨论】:
-
听起来像是面试题
-
你能澄清一下问题是什么吗?
-
那么第二个项目的第一个和最后一个项目中缺少哪些字母? '#' 没有意义。
-
可能有多个字母缺失。而且这不是一个面试问题,而是一个个人项目! :)
-
我怀疑你是否需要比
input.test(str.replace('#', '.*?')更复杂的东西。
标签: javascript regex string