Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need regex for all dynamic category items in node.js

I am working on node.js with regex. I have done the following:

 Category 1.2
 Category 1.3 and 1.4
 Category 1.3 to 1.4
 CATEGORY 1.3

The regex is

((cat|Cat|CAT)(?:s\.|s|S|egory|EGORY|\.)?)( |\s)?((\w+)?([.-]|(–)|(—))?(\w+))(\s+(to|and)\s(\w+)([.-]|(–)|(—))(\w+))?

However, I need a regex to also match the following strings:

 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 

How can I find all the category items (1.2,4.5,2.3,4.5 and 1.6) dynamically?Category grows depending on category available.

Note: No need matching Figure 1.2.

Any one assist me. Thanks in advance.

like image 653
Vanarajan Avatar asked Feb 20 '26 22:02

Vanarajan


1 Answers

I suggest using a simplified version of the regex:

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

See demo

If you need those hard spaces and en- and em-dashes, you can add them to the regex where necessary, like:

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

See another demo

Sample code:

    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]);
}
like image 138
Wiktor Stribiżew Avatar answered Feb 23 '26 12:02

Wiktor Stribiżew