【发布时间】: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