用于提取基于点概念的变量的动态Regex

Dynamic Regex for extracting dot notion based variables

本文关键字:变量 Regex 动态 提取 于点概 用于      更新时间:2023-09-26

我将使用什么Regex来返回包含scope.的所有字符串(用点表示法),但返回包括后面任意数量点的完整值。

例如,下面的代码不返回".string"部分。

> "scope.object.string".match(/(scope[.]'w+)/gi)

< ["scope.object"]

下面的代码将返回"scope.object.object2",因为我明确添加了第二个[.]'w+,它不是动态的。

> "scope.object.object2.string".match(/(scope[.]'w+[.]'w+)/gi)

< ["scope.object.object2"]

我该如何动态地执行此操作,以便从以下字符串中返回此值:

> "scope.object.string scope.object.object2.string scope.object.object2.object3.string".match(/newRegex/)

< ["scope.object.string", "scope.object.object2.string", "scope.object.object2.object3.string"]

如果您可以在同一调用中使用相同的regex从每个字符串中删除"scope."部分,那就更好了:

> "scope.object.string scope.object.object2.string scope.object.object2.object3.string".match(/newRegex/)

< ["object.string", "object.object2.string", "object.object2.object3.string"]

scope[.](?:'w+[.])*'w+

你可以用这个。如果要删除scope.,请使用

scope[.]((?:'w+[.])*'w+)

抓住第1组。参见演示。

https://regex101.com/r/pT4tM5/24

var re = /scope[.]((?:'w+[.])*'w+)/gm;
var str = 'scope.object.object2.string'nscope.object.object2';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}