【问题标题】:Implement a function that returns True if the given string matches the given wildcard pattern, False otherwise实现一个函数,如果给定的字符串与给定的通配符模式匹配,则返回 True,否则返回 False
【发布时间】:2017-07-25 13:59:01
【问题描述】:

实现一个函数,如果给定的字符串匹配给定的通配符模式,则返回 True,否则返回 False。

允许使用内置的split()indexOf()startsWith()endsWith()

这与我上一个非常相似,但我似乎仍然无法掌握它。这是我目前所拥有的

function matches(text, pattern) {
    var x = pattern.split("*");
    var y = (text.indexOf(x[0]) !== -1);
    for (i = 0; i< x.length; i++){
        if (y) {
            y = (text.indexOf(x[i]) !== -1);
        }
    }
    return y;
}

console.log(matches("lord of the rings", "lord*rings")); // Expected: True
console.log(matches("lord of the rings", "Lord*rings")); // Expected: False
console.log(matches("lord of the rings", "l*o*t*r")); // Expected: False
console.log(matches("lord of the rings", "l*o*t*r*s")); // Expected: True
console.log(matches("lord of the rings", "lord*")); // Expected: True
console.log(matches("lord of the rings", "*rings")); // Expected: True
console.log(matches("lord of the rings", "*the*")); // Expected: True
console.log(matches("lord of the rings", "*")); // Expected: True
console.log(matches("lord of the rings", "*z*")); // Expected: False

我要做的是隔离单词,然后检查每个单词,如果所有单词都存在,则返回true,或者如果至少其中一个不存在,则返回false。但是出了点问题,我不太明白是什么。

希望能提供解决方案或对我的代码提供反馈,请保持相当简单。 谢谢!

【问题讨论】:

  • “但是出了点问题” 太模糊了,没用。我会注意到您当前的代码没有做任何事情来检查各个部分是否在通配符字符串指定的 order 中。
  • 让我说我们不是来帮你做作业的;)
  • Lelio 这应该是什么意思?我不知道您是否可以在我的个人资料中看到它,但我只是为了好玩而编写代码并问这个只是因为我被卡住并且现在正在用头撞墙一段时间。这不是因为我有一个编码课,这是我的作业。

标签: javascript wildcard contains


【解决方案1】:
function matches(text, pattern) {
    while (text.length) {
        if (text[0] !== pattern[0] && pattern[0] !== '*')
            return false;

        text = text.slice(1);

        var wordAfterWildcard = pattern.split('*')[1];

        if (pattern[0] !== '*' || wordAfterWildcard && text.startsWith(wordAfterWildcard))
            pattern = pattern.slice(1);
    }
    return !(pattern && pattern.replace('*', ''));
}

// 我做了你的功课,因为我是个疯子。不是因为你。 // 享受...

【讨论】:

  • 嘿,抱歉,看看我给 Lelio 的答案,我真的只是输入了它。
  • 好吧,对不起:)
猜你喜欢
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
相关资源
最近更新 更多