javascript - 正则表达式编号后跟可能的单词列表

标签 javascript node.js regex

我知道有很多关于 RegEx 的问题,但我已经搜索了至少三天,但找不到解决我的问题的方法。

给出产品的标题我需要提取一些信息。 因此,为了做到这一点,我提供了一个单词列表,到目前为止一切顺利。但问题是我需要提取一个位于列表中任何单词之前的数字。

列表示例:

const words = ['temp', 'temperature', 'temperatures', 'degrees', 'heat', 'heating']

到目前为止,我所取得的成就是让正则表达式找到一些信息:

const textToSearch = 'Hair Dryer, 32JVT slopehill Professional Salon Negative Ions Hair Blow Dryer Powerful 1800W for Fast Drying, Lightweight Bioceramic with 3 Heating / 2 Speed/Cool Button, Magnetic Concentrator and Diffuser'
const regex = /(\d+(temp|\s(temp)|temperature|\s(temperature)|degrees|\s(degrees)|heat|\s(heat)|heating|\s(heating)))/g 
const found = textToSearch.match(regex);
if (found) {
  console.log(found[0]); 
}

但预期输出例如是 '32JVT' 而不是 3 Heating 另外,我不知道如何输入我从 API 收到的完整列表,因为该列表会有所不同和更改。 可能出现的其他问题是,该单词后面可能会跟有诸如 / 或任何其他符号之类的符号,我不知道这将如何与正则表达式混淆。

最佳答案

您可以从单词数组动态创建正则表达式,如下所示:

const words = ['temp', 'temperature', 'temperatures', 'degrees', 'heat', 'heating']
const textToSearch = 'Hair Dryer, 32JVT slopehill Professional Salon Negative Ions Hair Blow Dryer Powerful 1800W for Fast Drying, Lightweight Bioceramic with 3 Heating / 2 Speed/Cool Button, Magnetic Concentrator and Diffuser'

const regex = RegExp("\\b(\\d+(\\.\\d+)?)\\s+(" + words.join("|") + ")\\b", "gi");

console.log(textToSearch.match(regex));

反斜杠被转义,因为它们出现在字符串文字中。这也将数字与小数相匹配,并且要求数字后面的单词后面不能有更多字母。例如,即使 temp 位于单词列表中,3 tempament 也不会匹配。

如果您的单词列表包含在正则表达式中具有特殊含义的字符,例如 &|^、... ,然后确保转义这些。您可以使用escape function为此。

关于javascript - 正则表达式编号后跟可能的单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59992535/

相关文章:

javascript - 如何使用选择器使用 Playwright 查找框架(iframe)

node.js - 如何创建作业以将Elasticsearch索引中的所有文档作为数据流处理?

javascript - highcharts 使用变量作为图表标题

JavaScript 元素在部分 View 中格式化,但不起作用

node.js - Nodegit https 身份验证

Java RegEx 替换字符串中除单词之外的所有字符

regex - 如何使用正则表达式查找不属于某种模式的东西

regex - OS X sed -E 不接受扩展的正则表达式

javascript - nowjs的正确使用方式

javascript - 使用自调用匿名函数