I would like a RegExp to capture the number of pics, vids and writings in a string. That string could contain one, two, all or none of the categories. This is the closest I’ve got to those results.
Your help will be richly rewarded in a previous life. 😁
const text = "tt 3222 picsn" +
"tt 20 vidsn" +
"tt 1 writingn";
console.log(text);
const pattern = /(?<pics>(d+(?= pic)?))(?<vids>(d+(?= vid)?))(?<writings>(d+(?= writing)?))/gi;
matches = pattern.exec(text);
console.log(matches);
console.log("pics : " + matches.groups.pics); //expecting 3222
console.log("vids : " + matches.groups.vids); //expecting 20
console.log("writings : " + matches.groups.writings); //expecting 1
2
Answers
Your regular expression pattern is quite close, but it can be improved to capture the number of pics, vids, and writings in a string where they could appear in any order or combination. You can use a pattern like this:
Here’s how it works:
(?:...)
is a non-capturing group, allowing us to match but not capture optional parts.(?<pics>d+)
captures one or more digits for pics and stores it in the "pics" group.s*pics
matches optional whitespace followed by "pics."With this pattern, you can parse the text as follows:
This pattern will correctly capture the numbers of pics, vids, and writings in your input string, even if they appear in a different order or combination.
You could extract any pair of integer and word that occur at the end of a line, and construct an object from those pairs (as key/value pairs):