Search code examples
javascriptregexstringregex-groupstring-matching

Regex expression to match and store matched groups in an array


    let str = `!img2.png|width=83.33333333333334%!
    
                 !robot (f05f0216-caf4-4543-a630-99c2477849d5).png|width=400,height=400!
    
             fefeeef         !abc.pdf|width=200!
    
            !dfe.xlx           !abcd.xlx!
    `
    
    let str = str.replace(/\!(.*(jpg|png|gif|pdf|xlx))|(|width=})!\]/gm, function (match, capture) 
   {
                let imageConfig = [];
             //match and push in array
                imageConfig.push({file: 'abc.jpg' , width: 100, height:200});
                 
                return str; 
            })
                 
   Expected o/p:-
     imageConfig = [{file: 'abc.jpg' , width: 100, height:200}, {file: 'cdf.pdf' , width: 
                                200}, ....]  

This is what I tried, but regex is not giving correct match and its matched group:-

https://regex101.com/r/V6cA4i/1/


Solution

  • You may use this regex to build your output:

    /!([^|!]*(?:jpe?g|png|gif|pdf|xlx))(?:\|width=(\d*\.?\d+%?)(?:,height=(\d*\.?\d+%?))?)?!/g
    

    Updated RegEx Demo

    Code and Demo:

    let str = `!img2.png|width=83.33333333333334%!
        
                     !robot (f05f0216-caf4-4543-a630-99c2477849d5).png|width=400,height=400!
        
                 fefeeef         !abc.pdf|width=200!
        
                !dfe.xlx           !abcd.xlx!`;
                
    var re = /!([^|!]*(?:jpe?g|png|gif|pdf|xlx))(?:\|width=(\d*\.?\d+%?)(?:,height=(\d*\.?\d+%?))?)?!/g;
        
    let m;
    let imageConfig = [];
    
    while ((m = re.exec(str)) !== null) {
      imageConfig.push({file: m[1] , width: (m[2] || ''), height: (m[3] || '')});
    }
    console.log(imageConfig);