我正在将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})
我正在尝试在编辑器中执行“查找/替换”,以查找与key: value
词典相关的所有attrs
对。这是我得到的正则表达式:
/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)
任何帮助将不胜感激:)
答案 0 :(得分:1)
由于VS Code已经specify the location of your Django Settings File,因此您可以使用
"replacerules.rules": {
"Wrap the attrs with square brackets first": {
"find": "(attrs=){([^:{]+:*[^}]*)}",
"replace": "$1[[$2]]"
},
"Format attributes inside attrs": {
"find": "(?<=attrs=\\[\\[[^\\]]*(?:](?!])[^\\]]*)*),(\\s*)",
"replace": "],$1["
},
"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"
]
}
}
supports infinite-width lookbehind construct
输出:
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]])
答案 1 :(得分:0)
也许
(?<=attrs={|,)([^:}]*):([^:},]*)(?=}|,)
可能会更近一些。
如果您可能还有其他attrs
,则可能希望最初过滤掉其他那些。
如果您想探索/简化/修改表达式,可以 在右上角的面板上进行了说明 regex101.com。如果您愿意, 也可以在this link中观看它的匹配方式 针对一些样本输入。