skip to Main Content

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


  1. 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:

    const pattern = /(?:(?<pics>d+)s*pics)?s*(?:(?<vids>d+)s*vids)?s*(?:(?<writings>d+)s*writings)?/gi;
    

    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."
    • The same logic applies to vids and writings.

    With this pattern, you can parse the text as follows:

    const text = "tt                          3222 picsn" +
                 "tt                          20 vidsn" +
                 "tt                          1 writingn";
    console.log(text);
    
    const pattern = /(?:(?<pics>d+)s*pics)?s*(?:(?<vids>d+)s*vids)?s*(?:(?<writings>d+)s*writings)?/gi;
    
    let matches = pattern.exec(text);
    
    console.log("pics : " + (matches.groups.pics || "0")); // 3222
    console.log("vids : " + (matches.groups.vids || "0")); // 20
    console.log("writings : " + (matches.groups.writings || "0")); // 1
    

    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.

    Login or Signup to reply.
  2. 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):

    const text = "tt                          3222 picsn" +
                 "tt                          20 vidsn" +
                 "tt                          1 writingn";
    
    const regex = / (d+) (w+)n/gi;
    
    const res = Object.fromEntries(
        Array.from(text.matchAll(regex), ([, val, key]) => [key, +val])
    );
    
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search