用于匹配匹配组并将其存储在数组中的正则表达式

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}, ....]  

这是我尝试过的方法,但正则表达式没有给出正确的匹配及其匹配组:-

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

|需要转义

您必须转义“width”之前的 | 字符:

更正的正则表达式:

!(.*(jpg|png|gif|pdf|xlx))\|(width=.+)!

根据 regex101,您不必在开头转义 !。如果您的正则表达式方言需要,请随时再次添加 \!

可选宽度

如果只给出了高度,我们应该检查给定的宽度或高度:

!(.*(jpg|png|gif|pdf|xlx))(\|((width|height)=.+)!)?

您可以使用此正则表达式构建输出:

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

Updated RegEx 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);

下面的方法使用了两个正则表达式的组合,一个用于检索/matching the raw file data ...

/[!"]+([^!"]+)[!"]/gm

... 和第二个为了 help processing the final data structure ...

/^(?<fileName>[^.]+\.(?:jpg|png|gif|pdf|xlx))(?:\|(?:width=(?<width>.*?))?,?(?:height=(?<height>.*?))?)?$/

两个正则表达式都使用 Capturing groups the second one does it via named groups in order to create the final data structure just by Destructuring assignments,其中后者仅用于分配 widthheight 等字段,以防它们实际上可以被检索到。

有 3 个示例日志记录,逐步推进数据处理,以便了解所有涉及的数据处理步骤...

const sampleText = `!img2.png|width=83.33333333333334%!

             "!robot (f05f0216-caf4-4543-a630-99c2477849d5).png|width=400,height=400!" 

                  "!abc.pdf|width=200!"

        "!dfe.xlx"
  !"dfe.gif|height=400!"`;

// [https://regex101.com/r/XLNGBp/1]
const regXRawFileData = (/[!"]+([^!"]+)[!"]/gm);

// [https://regex101.com/r/XLNGBp/3]
const regXFileData = (/^(?<fileName>[^.]+\.(?:jpg|png|gif|pdf|xlx))(?:\|(?:width=(?<width>.*?))?,?(?:height=(?<height>.*?))?)?$/);

console.log(
  'match all data ...',

  Array.from(
    sampleText.matchAll(regXRawFileData)
  ).map(([match, rawData]) => rawData)
);
console.log(
  'match and filter all valid raw file data ...',

  [...sampleText.matchAll(regXRawFileData)]
    .map(([match, rawData]) => rawData)

    .filter(str => regXFileData.test(str))
);
console.log(
  'match, filter and map all valid file data ...',

  [...sampleText.matchAll(regXRawFileData)]
    .map(([match, rawData]) => rawData)

    .filter(str => regXFileData.test(str))
    .map(str => {
      const { fileName:file, width, height } = regXFileData.exec(str).groups;
      return {
        file,
        ...(width && { width } || {}),
        ...(height && { height } || {}),
      };
    })
);
.as-console-wrapper { min-height: 100%!important; top: 0; }