【问题标题】:Break down a string with regex用正则表达式分解字符串
【发布时间】:2021-11-17 00:36:45
【问题描述】:

我有一些示例字符串需要处理

string1 = "_Wondrous item, common (requires attunement by a wizard or cleric)_"
string2 = "_Weapon (glaive), rare (requires attunement)_"
string3 = "_Wondrous item, common_"

我想将它们分解成以下内容

group1 = {
  type: "Wonderous item"; 
  rarity: "common";
  attune: True
  class: "wizard or cleric"
  }
group2 = {
  type: "Weapon (glaive)";
  rarity: "rare";
  attune : True
  }
group3 = {
  type: "Wondrous item"
  rarity: "common"
  attune: False
  }

我目前拥有的正则表达式很混乱,可能效率低下,但它只会破坏第一个。

regex = /_(?<type>[^:]*),\s(?<rarity>[^:]*)\s\((?<attune>[^:]+)by a(?<class>[^:]*)\)_/U

添加详细信息

  • 这将在逐个处理文本文档时使用
  • 刺痛将在每个文档中出现一次
  • 如果有人好奇,我会在 Obsidian.MD 中使用它和模板工具
  • 是的,这是处理从 Reddit 捕获的 D&D 魔法物品

【问题讨论】:

    标签: javascript regex markdown


    【解决方案1】:

    使用您的模式获取 3 行的所有组:

    _(?<type>[^:]*?),\s+(?<rarity>[^:]*?)(?:\s+\((?<attune>[^:]+?)\s*(?:by\s+a\s+(?<class>[^:]*?))?\))?_
    
    • _(?&lt;type&gt;[^:]*?) 匹配 _,组 type 匹配除 : 以外的任何字符,非贪婪
    • ,\s 匹配 , 和一个空格字符
    • (?&lt;rarity&gt;[^:]*?)rarity 匹配除 : 非贪婪以外的任何字符
    • (?:非捕获组
      • \s\( 匹配一个空白字符和(
      • (?&lt;attune&gt;[^:]+?)\s* group attune 匹配除: non greedy 以外的任何字符
      • (?:by a\s+(?&lt;class&gt;[^:]*?))? 可选匹配 by a 和组 class 匹配除 : 非贪婪以外的任何字符
      • \)匹配)
    • )?_ 使外部组可选并匹配_

    查看regex demo

    使用groups 属性如果supported,您可以检查值并相应地更新对象。

    const regex = /_(?<type>[^:]*?),\s+(?<rarity>[^:]*?)(?:\s+\((?<attune>[^:]+?)\s*(?:by\s+a\s+(?<class>[^:]*?))?\))?_/;
    [
      "_Wondrous item, common (requires attunement by a wizard or cleric)_",
      "_Weapon (glaive), rare (requires attunement)_",
      "_Wondrous item, common_"
    
    ].forEach(s => {
      const m = s.match(regex);
      if (m) {
        if (m.groups.class === undefined) {
          delete m.groups.class;
        }
        m.groups.attune = m.groups.attune === undefined ? false : true;
        console.log(m.groups)
      }
    });

    请注意,在您的模式中,您希望阻止匹配否定字符类中的 :,但示例数据中没有 :

    对于第一个否定字符类,您可以将其更改为不匹配逗号,对于其他排除匹配括号以获得相同的结果。

    这样并不是所有的量词都必须是非贪婪的,它可以防止一些不必要的回溯。

    _(?<type>[^,]*),\s(?<rarity>[^:()]*)(?:\s\((?<attune>[^()]+?)\s*(?:by a\s+(?<class>[^()]*))?\))?_
    

    查看另一个regex demo

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 2011-09-28
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多