简体   繁体   English

ES6 / JS:用条件链替换 delve 的正则表达式

[英]ES6 / JS: Regex for replacing delve with conditional chaining

How to replace delve with conditional chaining in a vs code project?如何在 vs 代码项目中用条件链接替换 ​​delve?

eg例如

delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")

desired result期望的结果

seo?.meta
item?.image.data.attributes.alternativeText

Is it possible using find/replace in Visual Studio Code?是否可以在 Visual Studio Code 中使用查找/替换? 在此处输入图像描述

I propose the following RegEx:我提出以下正则表达式:

delve\(\s*([^,]+?)\s*,\s*['"]([^.]+?)['"]\s*\)

and the following replacement format string:以及以下替换格式字符串:

$1?.$2

Explanation: Match delve( , a first argument up until the first comma (lazy match), and then a second string argument (no care is taken to ensure that the brackets match as this is rather quick'n'dirty anyways), then the closing bracket of the call ) .说明:匹配delve( ,第一个参数直到第一个逗号(惰性匹配),然后是第二个字符串参数(不注意确保括号匹配,因为这无论如何都是相当快的'n'dirty),然后调用的右括号) Spacing at reasonable places is accounted for.考虑到合理位置的间距。

which will work for simple cases like delve(someVar, "key" ) but might fail for pathological cases;这将适用于像delve(someVar, "key" ) 这样的简单案例,但对于病理案例可能会失败; always review the replacements manually.始终手动检查替换。

Note that this is explicitly made incapable of dealing with delve(var, "abc" ) because as far as I know, VSC format strings don't support "joining" variable numbers of captures by a given string.请注意,这明确地无法处理delve(var, "abc" ) 因为据我所知,VSC 格式字符串不支持给定字符串“加入”可变数量的捕获。 As a workaround, you could explicitly create versions with two, three, four, five... dots and write the corresponding replacements.作为一种解决方法,您可以显式创建具有两个、三个、四个、五个...点的版本并编写相应的替换。 The version for two dots for example looks as follows:例如,两个点的版本如下所示:

delve\(([^,]+?)\s*,\s*['"]([^.]+?)\.([^.]+?)['"]\s*\)

and the format string is $1?.$2?.$3 .格式字符串是$1?.$2?.$3

You write:你写:

eg例如
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")
desired result期望的结果
seo?.meta
item?.image.data.attributes.alternativeText

but I highly doubt that this is intended, because delve(item, "image.data.attributes.alternativeText") is in fact equivalent to item?.image?.data?.attributes?.alternativeText rather than the desired result you describe.但我高度怀疑这是有意为之,因为delve(item, "image.data.attributes.alternativeText")实际上等同于item?.image?.data?.attributes?.alternativeText而不是您描述的预期结果。 To make it handle it that way, simply replace [^.] with .要使其以这种方式处理,只需将[^.]替换为. to make it accept strings containing any characters (including dots).使其接受包含任何字符(包括点)的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM