需要regex的所有动态类别项目在node.js

Need regex for all dynamic category items in node.js

本文关键字:项目 node js 动态 regex 需要      更新时间:2023-09-26

我正在用regex处理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

看到演示

如果需要硬空格和连字符和连字符,可以在需要的地方将它们添加到正则表达式中,例如:

/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 -然后匹配所有类别(数字-句号-数字)并将它们放在一个数组中。

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