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

标签 javascript regex node.js

我正在使用正则表达式开发 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/

相关文章:

node.js - Firebase 函数 : cannot read property 'user_id' of undefined

javascript - 图表上的动态行数

javascript - 正则表达式允许十进制数不起作用

javascript - 如何清除容器控件中的所有值

javascript - 模式密码 JavaScript

jquery - 正则表达式和 jQuery : lower case

node.js - 如何用html替换jade

node.js - 事件发生后如何在恢复中获得响应体?

javascript - 如何为 gupshup 聊天添加延迟,以便聊天机器人在 5 秒后打开?

javascript - 多个嵌套 Mongoose Promise 的结构