【问题标题】:How to check a string includes or doesnot include certain words from array?如何检查字符串是否包含数组中的某些单词?
【发布时间】:2021-07-21 11:26:36
【问题描述】:

假设我有两个数组:

const rejectBill = ['cancel', 'delete', 'discard', 'erroneously']

const readBill = ['bill','account','amount']

我有一个字符串,

const stringBill = 'Read bill from text to be cancelled'

我想检查 bill 是否包含 readBill 中的单词然后返回 true,但如果它还包含 rejectBill 中的单词则返回 false。

为此我尝试过:

let stringSatus = readBill.some(keyword => stringBill.toLowerCase().includes(keyword.toLowerCase())) && 
                   !rejectBill.some(keyword => stringBill.toLowerCase().includes(keyword.toLowerCase()))

但在 stringSatus 的控制台上,它给出了 false。

当字符串包含来自 readBill 数组的单词不包含来自rejectBill 数组的单词时,我希望stringStatus 为真,当字符串包含来自rejectBill 的单词时,我希望stringStatus 为假。

如果有人需要更多信息,请告诉我。

【问题讨论】:

  • stringBill 具有来自readBill'bill' 和来自rejectBill'cancel',因此条件返回false
  • 您想检查全字匹配还是没有注意到字符串中的cancelled?如果您想将 cancelcancelled 视为不同的词,则必须使用 word boundaries 和正则表达式
  • 如果你想检查准确的单词匹配,你可以做const words = new Set(stringBill.toLowerCase().split(' ')); readBill.some(word => words.has(word.toLowerCase())) && !rejectBill.some(word => words.has(word.toLowerCase()))

标签: javascript node.js arrays string


【解决方案1】:

使用正则表达式

我基于string[] 即时创建了regex,并测试string 是否通过regex

const rejectBill = ['cancel', 'delete', 'discard', 'erroneously'];

const readBill = ['bill', 'account', 'amount'];

const stringBill = 'Read bill from text to be cancelled';

var rejectBillRegex = new RegExp(rejectBill.map(t => `\\b${t}\\b`).join('|'), 'i'),
  readBillRegex = new RegExp(readBill.map(t => `\\b${t}\\b`).join('|'), 'i');

var stringSatus = readBillRegex.test(stringBill) && !rejectBillRegex.test(stringBill);
console.log(stringSatus)

【讨论】:

  • 试试'Pay the bill or cancel'
【解决方案2】:

使用String#splitSet


您可以使用String#split 按空格拆分字符串,然后使用从列表中构造的Set 检查拆分后的数组是否包含Set 中存在的任何(使用Array#some)字符串。

注意:目前区分大小写,您可以使用toLowerCase()toUpperCase() 使其不区分大小写。

const 
  rejectBill = ["cancel", "delete", "discard", "erroneously"],
  readBill = ["bill", "account", "amount"],
  stringBill = "Read bill from text to be cancelled",
      
  strInList = (str, lst, set = new Set(lst)) => str.split(" ").some((s) => set.has(s)),

  isRead = strInList(stringBill, readBill) && !strInList(stringBill, rejectBill);

console.log(isRead);

【讨论】:

    【解决方案3】:

    通过快速查看您的代码,它似乎可以正常工作。您的示例“从要取消的文本中读取帐单”返回 false,因为它检测到单词“'cancel'led”。如果您要从“取消”中删除“取消”,它将返回 true。如果您要检查空格,我会在 readBill 和 rejectBill 中的每个值之后添加一个空格,如下所示:

    const rejectBill = ['cancel ', 'delete ', 'discard ', 'erroneously '];
    const readBill = ['bill ', 'account ', 'amount '];
    

    当 stringBill 以其中一个单词结尾时,您还需要添加故障保护。这可以通过检查字符串的最后一个单词 stringBill 轻松实现。如果您有任何问题,请随时发表评论,我会尽我所能为您提供帮助!

    【讨论】:

    • 为关键字添加空格是个糟糕的主意。
    • 我不得不同意你的观点,我应该提出一个更好的实施方案。我认为 OP 最初只是犯了一个错误,即在“已取消”中没有看到取消。
    猜你喜欢
    • 2015-03-14
    • 2011-03-31
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2013-10-21
    相关资源
    最近更新 更多