当前位置: 代码迷 >> JavaScript >> 需要node.js中所有动态类别项的正则表达式
  详细解决方案

需要node.js中所有动态类别项的正则表达式

热度:92   发布时间:2023-06-13 12:09:20.0

我正在使用正则表达式在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)?类别根据可用类别增长。

注意:不需要匹配Figure 1.2

任何人都帮助我。 提前致谢。

我建议使用正则表达式的简化版本:

/cat(?:s?\.?|egory)?[ ]*(?:[ ]*(?:,|and|to)?[ ]*\d(?:\.\d+)?)*/gi

如果你需要那些硬空间和en-em-das,你可以在必要时将它们添加到正则表达式,例如:

/cat(?:s?\.?|egory)?[ —–\xA0]*(?:[ —–\xA0]*(?:,|and|to)?[  —–\xA0]*\d(?:\.\d+)?)*/gi

示例代码:

  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]); } 

中断试图解决这个问题,并看到stribizhev为你解决了这个问题。 只想分享我要去的地方:

var lines = 
 'Category 1.2\n'+
 'Category 1.3 and 1.4\n'+
 'Category 1.3 to 1.4\n'+
 'CATEGORY 1.3\n'+
 'Category 1.2, 1.3 and 1.5\n'+
 'Category 1.2, 4.5, 2.3 and 1.6\n'+
 'Category 1.2, 4.5, 2.3, 4.5 and 1.6\n'+
 'Figure 1.2 and 1.4\n'

document.write(lines.replace(/^(?!category).*$/igm, '').match(/(\d+\.\d+)/gm));

此片段删除所有不包含单词'category'的行(如'Figure ...'之类的行) - replace - 然后匹配所有类别(数字 - 句号 - 数字)并将它们放入数组中。

我知道你的正则表达式比这复杂得多,但这似乎做你要求的,非常简单......只是分享;)

问候