简体   繁体   English

使用正则表达式查找字符串中的可变字母组

[英]Using regexp to find variable group of letters in a string

I'm doing a basic algorithm scripting challenge on FCC and I want to return true if a string in a first element of an array contains all of the letters of the string in the second element of the array, or false otherwise.我正在 FCC 上做一个基本的算法脚本挑战,如果数组的第一个元素中的字符串包含数组的第二个元素中的字符串的所有字母,我想返回true否则返回false

I've written some code for this.我为此编写了一些代码。 However I can't seem to pass one test:但是我似乎无法通过一项测试:

mutation(["hello", "Hello"])

I've tried removing the global flag and have tried using constructor notation and literal notation based on recommendations from the FCC community, but to no avail.我尝试删除全局标志,并尝试根据 FCC 社区的建议使用构造函数表示法和文字表示法,但无济于事。

This is the code:这是代码:

function mutation(arr) {
  let patt = new RegExp("[arr.1]", "i");
  return patt.test(arr[0]);

}

mutation(["hello", "Hello"])

The function is supposed to return true instead it returns false .该函数应该返回true而不是返回false What is wrong with my code?我的代码有什么问题?

new RegExp("[arr.1]", "i") uses [arr.1] (literally) as the regular expression, which is why it doesn't work. new RegExp("[arr.1]", "i")使用[arr.1] (字面意思)作为正则表达式,这就是它不起作用的原因。

I wouldn't use a regular expression for this, it's simpler to do it directly.我不会为此使用正则表达式,直接执行更简单。 For instance:例如:

function mutation(arr) {
  const lc = arr[0].toLowerCase();
  return [...arr[1].toLowerCase()].every(ch => lc.includes(ch));
}

...or to make searching the string not be a linear search: ...或者使搜索字符串不是线性搜索:

function mutation(arr) {
  const chars = new Set([...arr[0].toLowerCase()]);
  return [...arr[1].toLowerCase()].every(ch => chars.has(ch));
}

...but if you have to use regex, you could generate an array with all the permutations of arr[1] ( ["Hello", "oHell", "loHel", ...] ) (perhaps using the answers here ) then create your regular expression using beginning/ending anchors ( ^ , $ ) and alternations ( | ) of all the permutations: ...但是如果你必须使用正则表达式,你可以生成一个包含arr[1] ( ["Hello", "oHell", "loHel", ...] ) 的所有排列的数组(也许使用这里的答案) 然后使用所有排列的开始/结束锚点 ( ^ , $ ) 和交替 ( | ) 创建正则表达式:

let permutations = /*...use the linked answers to create permutations...*/;
let patt = new RegExp("^(?:" + permutations.join("|") + ")$", "i");

If arr[1] may contain characters that are special in regular expressions, you'll need to escape them (perhaps using one of the answers here ):如果arr[1]可能包含正则表达式中的特殊字符,则需要对它们进行转义(可能使用此处的答案之一):

let patt = new RegExp("^(?:" + permutations.map(escapeRegExp).join("|") + ")$", "i");

(Again: There is no built-in escapeRegExp , see the answers to the question linked above for how to create one.) (同样:没有内置的escapeRegExp ,请参阅上面链接的问题的答案,了解如何创建一个。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM