【问题标题】:Complex Regex optional search with multiple returned objects具有多个返回对象的复杂正则表达式可选搜索
【发布时间】:2021-04-01 16:51:11
【问题描述】:

我正在尝试让以下内容在某些条件下进行搜索。 总会有给定的文件名,其他是可选的。

[[File:HumanMaleDiagram.png|right|300px|thumb|A diagram of a male human.]]

第二项可以是[left, right, center]或可选,大小可选(px或%),thumb可选,最后的alt文本可选。

我用过:

var imageFinder = /\|\s*\[\[File\:([\w\-\_\. ]+)\|*(?=[right|left|center]*)\|*(?=[\w]*px)\|*(?=[thumb]*)\|*(?=[\w\.\s]*)\]\]/gi

返回 $1...$5

所以我在管道上使用了前瞻的“?=”和“*”,但没有找到它。

最近几天一直在愤怒地使用正则表达式。我所有其他人都在工作(他们比这小),但我们将不胜感激。

在 JavaScript 中执行此操作。

感谢任何可以提供帮助的人。

【问题讨论】:

    标签: javascript regex regex-lookarounds regexp-replace


    【解决方案1】:

    您可以将每个部分设为可选,因此您无需使用前瞻。

    我建议使用named capturing groups(但这不是必需的)。

    \[\[File:[^|]+(?:\|(?<align>left|right|center))?(?:\|(?<size>\d+(?:px|%)))?(?:\|(?<thumb>thumb))?(?:\|(?<alt>[^|]+))?\]\]
    

    See this at work on regex101

    【讨论】:

      【解决方案2】:

      这是一个使用exec() 的快速sn-p,解构结果,并返回一个值为undefined 的对象,用于丢失任何捕获组。

      我不确定管道是否是永久性的,即使它们之间的字符串不存在。

      const regex = /(?:File:([\w\s-]+\.\w{3,4}))\|(right|left|center)?\|(\d+(?:px|%))?\|(thumb)?\|(.*[^\]])?/i
      
      const parse = (str) => {
        const [_, file, align, width, thumb, desc] = regex.exec(str);
        return { file, align, width, thumb, desc };
      }
      
      const
        str1 = '[[File:HumanMaleDiagram.png|right|300px|thumb|A diagram of a male human.]]',
        str2 = '[[File:Human_23.mp4|left|300%||A diagram of a male human.]]',
        str3 = '[[File:HumanMDiagram.jpeg||300%||A diagram of a human, male.]]';
      
      console.log(parse(str1));
      console.log(parse(str2));
      console.log(parse(str3));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      字符串操作

      鉴于您的字符串由| 字符分隔,您可以放弃正则表达式并使用标准字符串操作。

      • 剪掉前导和尾随 [[]]
      str = str.replace(/(?:^\[\[)|(?:\]\]$)/g, '')
      
      • | 字符处拆分结果。
      str.split('|')
      

      const parse = (str) => {
        str = str.replace(/(?:^\[\[)|(?:\]\]$)/g, '');
        return str.split('|');
      }
      
      const
        str1 = '[[File:HumanMaleDiagram.png|right|300px|thumb|A diagram of a male human.]]',
        str2 = '[[File:Human_23.mp4|left|300%||A diagram of a male human.]]',
        str3 = '[[File:HumanMDiagram.jpeg||300%||A diagram of a human, male.]]';
      
      console.log(parse(str1));
      console.log(parse(str2));
      console.log(parse(str3));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        相关资源
        最近更新 更多