【发布时间】:2019-01-12 18:48:54
【问题描述】:
我正在解决Coderbyte Challenge - Questions Marks 当我在浏览器中运行我的代码时,一切正常,但是,一旦我在 coderbyte 网站上运行它就会引发错误。
挑战是:
让 QuestionsMarks(str) 函数接受 str 字符串参数, 其中将包含单个数字、字母和问号, 并检查每对之间是否正好有 3 个问号 两个数字加起来为 10。如果是这样,那么您的程序应该返回 字符串为真,否则返回字符串为假。如果有 不是字符串中任何两个加起来为 10 的数字,那么你的 程序也应该返回 false。
例如:如果 str 是 "arrb6???4xxbl5???eee5" 那么你的程序 应该返回 true 因为之间正好有 3 个问号 6 和 4,以及 5 和 5 之间的 3 个问号在结尾 字符串。
使用下面框中的参数测试功能来测试您的代码 有不同的论点。
测试用例是:
"arrb6???4xxbl5???eee5" 真
"aa6?9" 假
"acc?7??sss?3rr1??????5" true
我对此的解决方案是使用 RegExp 来解决挑战。当我在浏览器中运行下面的代码时,它运行良好,但是 Coderbyte 控制台每次都会抛出一个错误:
/tmp/009904362/main.js:11 clean = clean.match(/d(???)d/gi); ^SyntaxError: 无效的正则表达式:/d(???)d/
这是我的代码 -
function QuestionsMarks(str) {
//create a "clean" array containing only the numbers and question marks from str
var result;
let clean = str.match(/[0-9?]/g);
// join() the array back in to the string
clean = clean.join("");
// use match() to return an array of pairs that match the pattern d???d
clean = clean.match(/d(\?\?\?)d/gi);
//create a function sumCheck() that converts first and last char of every array string to Number and checks if the sum of digits is 10
//using forEach() run the sumcheck() on all strings in the array
clean.forEach(sumCheck);
function sumCheck(string){
if((Number(string.charAt(0)) + Number(string.charAt(string.length - 1))) == 10){
result = true;
}else{
result = false;
}
}
return result;
}
QuestionsMarks("acc?7??sss?3rr1??????5");
【问题讨论】:
-
我不确定是什么导致了错误,从错误消息中看起来斜杠已从表达式中删除,无论如何,您的模式不正确,以匹配您需要使用的数字
\d不仅仅是d。试试new RegExp("\\d(\\?\\?\\?)\\d") -
不知道是什么导致了错误。我认为它不应该给出这个错误。无论如何,尝试做类似
/\d([?][?][?])\d/的事情,看看它是否有效(这是一个丑陋的黑客)。 -
模式
\\d(\\?\\?\\?)\\d不起作用,它不适用于第二个和第三个问号由字符分隔的第三种情况。 -
@UnbearableLightness:字符串在测试模式之前从字母中清除。
-
是的,这可能是一种方法,但似乎有点不必要。
标签: javascript regex design-patterns interpreter