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.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With