[英]RegEx number followed by a list of possible words
我知道有很多关于 RegEx 的问题,但我已经搜索了至少三天,但找不到解决我的问题的方法。
给出一个产品的标题,我需要提取一些信息。 所以为了做到这一点,我得到了一个单词列表,到目前为止一切都很好。 但问题是我需要提取一个数字,该数字将出现在列表中的任何单词之前。
列表示例:
const words = ['temp', 'temperature', 'temperatures', 'degrees', 'heat', 'heating']
到目前为止,我所取得的成就是给 regEx 找到一些信息:
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 收到的完整列表,因为该列表会有所不同和变化。 可能出现的其他问题是,单词后面可能跟有像/
或任何其他符号这样的符号,我不知道这将如何与正则表达式混淆。
您可以从单词数组动态创建一个 RegExp,如下所示:
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 temperament
。
如果您的单词列表将包含在正则表达式中具有特殊含义的字符,例如&
、 |
, ^
, ...,然后一定要避开这些。 您可以为此使用转义函数。
我会尝试使用以下语法:
([1-9]+ +[Hh]eating)
每个单词。 它由一个或两个数字( +
表示前一项中的一个或多个)介于 1-9(实际上介于 01 和 99 之间)、一个或多个空格以及术语加热或加热组成。
这对我来说很好用你的例子。 你可以对其他单词做同样的事情,应该会得到一个不错的结果。
您可以使用(\\d*\\s|)
来匹配单词前面的数字。 我认为您的搜索也不区分大小写。
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 34 Heating / 2 Speed/Cool Button, Magnetic Concentrator and Diffuser, 87 degrees' const regex = /(\\d*\\s|)(temp|temperature|temperatures|degrees|heat|heating)/gi; const found = textToSearch.match(regex); if (found) { console.log(found); }
const words = ['temp', 'temperature', 'temperatures', 'degrees', 'heat', 'heating']; const words_re = words.join('|') 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 = new RegExp('\\\\d+\\\\s*\\\\b(?:' + words_re + ')\\\\b', 'gi'); console.log(textToSearch.match(regex)[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.