【问题标题】:How do I find an exact substring match in an array in JavaScript?如何在 JavaScript 中的数组中找到精确匹配的子字符串?
【发布时间】:2022-11-23 22:02:09
【问题描述】:

我在尝试查找字符串中的子字符串时遇到问题。这不是使用 indexOfmatch()test()includes() 的简单子字符串匹配。我试过使用这些但无济于事。我在数组中有一堆字符串,然后需要使用 filter() 方法或 some() 方法来查找子字符串匹配。

我需要用命令匹配数组中的一个字符串;

我尝试了以下但它不起作用:

let matchedObject;
const command = "show vacuum bed_temperature_1";
const array = [ "show vacuum", "show system", "set system", "set vacuum" ];

if (array.some((a) => command.includes(a))) {
    // This matches an element in the array partially correctly, only that it also matches with one of the unacceptable strings below.
}

可接受的字符串

元素“show vacuum”与命令完全匹配。

const example1 = "show vacuum";
const example2 = "show vacuum bed_temperature_1";
const example3 = "show vacuum bed_temp_2";
const example4 = "show vacuum bed_temp3";

不可接受的字符串

const example 1 = "show vacuums bed_temperature_1";
const example 2 = "shows vacuum bed_temperature_1";
const example 3 = "show vauum bed_temp3";

【问题讨论】:

  • 不确定您的 includes 行如何不起作用。不确定你为什么这样做 if() match line include 的问题是它会寻找那个字符串,它不会关心“foo”在“food”中。如果需要精确匹配,则需要使用正则表达式。
  • 我的不好,我意识到我使用了过于复杂的代码并稍微简化了它。

标签: javascript arrays substring indexof


【解决方案1】:

看起来您需要一个带有单词边界 的正则表达式。您可以从数组中动态创建此正则表达式:

const array = [ "show vacuum", "show system", "set system", "set vacuum" ];

const re = RegExp('\b(' + array.join('|') + ')\b')

test = `
show vacuum bed_temperature_1
show vacuum bed_temp_2
show vacuum bed_temp3
show vacuums bed_temperature_1
shows vacuum bed_temperature_1
show vauum bed_temp3
`

console.log(test.trim().split('
').map(s => s + ' = ' + re.test(s)))

注意:如果您的array 包含正则表达式特有的符号,则它们应该是正确的escaped

【讨论】:

  • 这应该伴随着关于使用 array.join('|') 之类的东西合成正则表达式的警告,因为您打算创建一个与数组元素的文字文本匹配的正则表达式,但不会转义任何特殊的正则表达式语法或这些数组元素的文本中可能出现的字符。
  • @Wyck:好点,补充道。
【解决方案2】:
const array = ["show vacuum", "show system", "set system", "set vacuum"];
const outputString = "show vacuum bed_temperature_1";

array.forEach((key) => {
  const regex = new RegExp(`${key}`);
  if (regex.test(outputString)) {
    console.log(key, "matched");
  } else {
    console.log(key, "not matched");
  }
})

【讨论】:

    猜你喜欢
    • 2011-05-05
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多