查找和替换键:值对

Finding and replacing key: value pairs

我正在将 Python 库移植到 JavaScript / TypeScript。为了帮助自己,我正在尝试开发各种正则表达式规则,我可以将这些规则应用于自动转换大量语法的文件,至少让我接近,在需要的地方清理。

我有以下示例:

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

this.mk(attrs={keyCollection.key: 40}))
this.mk(attrs={keyCollection.key: 50, override.key: override.value})
this.mk(attrs={keyCollection.key: 60, 
               override.key: override.value})

我正在尝试在我的编辑器中执行 Find/Replace,以查找与 attrs 词典关联的所有 key: value 对。这是我得到的正则表达式:

/attrs={(.+?):\s*(.+?)}/gms

我想把它转换成这样:

this.mk(attrs=[[keyCollection.key, 40]]))
this.mk(attrs=[[keyCollection.key, 50], [override.key, override.value]])
this.mk(attrs=[[keyCollection.key, 60], 
               [override.key, override.value]])

我在确定正则表达式以获取重复键:值组时遇到了问题,然后我还无法确定如何在替换中使用这些重复组。

(我的编辑器是 VSCode,但我使用这个漂亮的扩展 运行 这些修改:https://marketplace.visualstudio.com/items?itemName=bhughes339.replacerules

任何帮助将不胜感激:)

也许,

(?<=attrs={|,)([^:}]*):([^:},]*)(?=}|,)

可能更近一些。

如果您可能有其他 attrs,您可能希望首先过滤掉其他的。


If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


因为 VS Code 已经 你可以使用

"replacerules.rules": {
    "Wrap the attrs with square brackets first": {
        "find": "(attrs=){([^:{]+:*[^}]*)}",
        "replace": "[[]]"
    },
    "Format attributes inside attrs": {
        "find": "(?<=attrs=\[\[[^\]]*(?:](?!])[^\]]*)*),(\s*)",
        "replace": "],["
    },
    "Replace colons with commas inside attrs": {
        "find": "(?<=attrs=\[\[[^\]]*(?:](?!])[^\]]*)*):",
        "replace": ","
    }
}

"replacerules.rulesets": {
    "Revamp attrs": {
        "rules": [
            "Wrap the attrs with square brackets first",
            "Format attributes inside attrs",
            "Replace colons with commas inside attrs"
        ]
    }
}

Step #1 regex demo

Step #2 regex demo

Step #3 regex demo

输出:

this.mk(attrs=[[keyCollection.key, 40]]))
this.mk(attrs=[[keyCollection.key, 50], [override.key, override.value]])
this.mk(attrs=[[keyCollection.key, 60], 
               [override.key, override.value]])