【问题标题】:How to find list of words in array of string using regex [duplicate]如何使用正则表达式在字符串数组中查找单词列表[重复]
【发布时间】:2021-06-17 16:25:02
【问题描述】:

我有这个段落数组。我需要使用 Regex 查看特定单词是否在数组中。我是正则表达式的新手,到目前为止我已经尝试过

claims.forEach((d) => {
  const regexp = /[protein]+/i
  const result = d.match(regexp)
  console.log(result)
})

但是,这会返回“蛋白质”一词的每次出现,即使它的前 3 个字母也是如此。

我如何使用正则表达式取出任何出现的不只是蛋白质,而是单词列表?

这是数组:

["UPDATE | Due to high demand, please allow extra time for your delivery Dismiss", "HIGH IN PROTEIN & FIBRE", "<160 CALORIES", "GLUTEN & PALM OIL FREE", "NUT BUTTER FILLED", "This nutty, chewy ball with a salty kick is danger…ng or afternoon, to satisfy those sweet cravings.", "High in Protein & Fibre", "<160 Calories", "Gluten & Palm Oil Free", "Nut Butter Filled", "Packed with protein, full of fibre and nutritional…erfect pick me up to energise and keep you going!", "158kcal\n9.2g Protein\nVegetarian\nGluten Free\nPalm Oil Free\nHigh in Fibre", "Almonds (26%), Cashews (18%), Brown Rice Syrup, Wh…vourings, Antioxidant: Natural Mixed Tocopherols.", " ", "  Kosher", "VEGAN", "VEGAN", "By signing up to our newsletter, you agree for you…rselves regarding Bounce Brands and its partners.", "Fuelling your day the natural way!"]

【问题讨论】:

  • [] 表示“括号内的任何字符”。为什么需要正则表达式来查找字符串的子字符串?只需使用s.includes("word")s.indexOf("word")。如果你想尊重单词边界,那么你可以使用正则表达式,s.match(/\bword\b/g)

标签: javascript reactjs regex


【解决方案1】:

您可以使用includesfilter 函数来获取结果。

const results = claims.filter((d) => {
   d.toLowerCase().includes('protein')
})
console.log(results)

如果你还想使用正则表达式,你应该删除[ & ]

  claims.forEach((d) => {
     const regexp = /protein/i
     const result = d.match(regexp)
     console.log(result)
  })

【讨论】:

  • 问题是要求不区分大小写(参见正则表达式末尾的i),而普通的includes 不能满足这一要求。请注意,使用toLowerCase() 不是启用不区分大小写的全局正确解决方案。
  • 这也不考虑单词边界
  • localeCompare() 将是获得良好答案的有效方法,而 .toLowerCase() 则不是。
  • 感谢您的回答,我如何将正则表达式单词链接在一起?
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2019-02-20
  • 2021-12-26
相关资源
最近更新 更多