我正在使用正则表达式开发 node.js。我做了以下事情:
Category 1.2
Category 1.3 and 1.4
Category 1.3 to 1.4
CATEGORY 1.3
正则表达式是
((cat|Cat|CAT)(?:s\.|s|S|egory|EGORY|\.)?)( |\s)?((\w+)?([.-]|(–)|(—))?(\w+))(\s+(to|and)\s(\w+)([.-]|(–)|(—))(\w+))?
但是,我需要一个正则表达式来匹配以下字符串:
Category 1.2, 1.3 and 1.5
Category 1.2, 4.5, 2.3 and 1.6
Category 1.2, 4.5, 2.3, 4.5 and 1.6
Figure 1.2 and 1.4 - no need
我如何动态地找到所有类别项目(1.2、4.5、2.3、4.5 和 1.6)?类别根据可用类别增长。
注意:不需要匹配图1.2
。
任何人都可以帮助我。 提前致谢。
最佳答案
我建议使用正则表达式的简化版本:
/cat(?:s?\.?|egory)?[ ]*(?:[ ]*(?:,|and|to)?[ ]*\d(?:\.\d+)?)*/gi
参见 demo
如果您需要这些硬空格和破折号,您可以在必要时将它们添加到正则表达式中,例如:
/cat(?:s?\.?|egory)?[ —–\xA0]*(?:[ —–\xA0]*(?:,|and|to)?[ —–\xA0]*\d(?:\.\d+)?)*/gi
参见 another demo
示例代码:
var re = /cat(?:s?\.?|egory)?[ —–\xA0]*(?:[ —–\xA0]*(?:,|and|to)?[ —–\xA0]*\d(?:\.\d+)?)*/gi;
var str = 'Figure 1.2. Category 1.2 Figure 1.2. \nFigure 1.2. Category 1.3 and 1.4 Figure 1.2. \nFigure 1.2. Category 1.3 to 1.4 Figure 1.2. \nFigure 1.2. CATEGORY 1.3 Figure 1.2. \n\nFigure 1.2. Category 1.2, 1.3 and 1.5 Figure 1.2. \nFigure 1.2. Category 1.2, 4.5, 2.3 and 1.6 Figure 1.2. \nFigure 1.2. Category 1.2, 4.5, 2.3, 4.5 and 1.6 Figure 1.2. \nFigure 1.2. Category 1.3 — 1.4 Figure 1.2. \nFigure 1.2. Category 1.3 – 1.4 Figure 1.2. \nFigure 1.2. Category 1.3 – 1.4 Figure 1.2. (with hard space)';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
document.write("<br>" + m[0]);
}
关于javascript - node.js 中的所有动态类别项目都需要正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471544/