正则表达式:Javascript中的否定Lookbehind + Lookahead

问题描述 投票:0回答:2

我将尝试围绕这个在服务器端工作的正则表达式。

new RegExp(/(?<!:\s*\w*)\w+(?=\s*[,}])/g)

它遍历一个看起来像这样的字符串:

{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}

它匹配没有子键或值的所有键。但这在Javascript中不起作用,因为Javascript不允许RegExp的Lookbehind部件。我想知道Javascript中是否有解决方法。我所读到的只是Lookbehind而不是Lookbehind + Lookahead。

你可以在这里玩。 regex101.com

编辑:更多信息:这个正则表达式是一个解析器的一部分,它解析一个简约的查询语言 - 一个GraphQL和MondoDB-Queries的嵌合体。

有一个字符串进入的功能

{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}

并输出一个对象。所有没有子键或值的键实际上以','或'}'结尾的键都替换为:true。最后,输出看起来像这样:

{
Product: {
    id: { $lt: 10 },
    title: true,
    categories: {
        name: true
    }
}

}

我试图让它成为客户端。

javascript php regex
2个回答
0
投票

我认为这解决了你的问题

const regex = /[{,]\s*\w+(?=[,}])/g
const str = `{Product{id{$lt:10,$gt:20},title,other,categories{id,name}}}`
const result = str.replace(regex, (...a) =>  `${a[0]}:true`)
console.log(result)

0
投票

不确定你想要的结果,但这是你的正则表达式 不使用lookbehind断言。 如果您感兴趣,整个想法就是移动比赛位置 超出你不想匹配的东西。

这样做。

 (?:                           # -------------
      ( : \s* \w+ )                 # (1), Move past this
   |                              # or,
      ( \w+ )                       # (2), To get to this
 )                             # -------------
 (?= \s* [,}] )                # Common lookahead assertion

通常,您只需使用JS回调功能来找出匹配的内容。

var regex = /(?:(:\s*\w+)|(\w+))(?=\s*[,}])/g;
var str = '{Product{id{$lt:10,$gt:20},title,other,categories/{id,name}}}';

var newString = str.replace(
       regex,
       function(match, p1, p2) {  // Callback function
         if (p1) return p1;       // Group 1, return it unchanged
         return p2 + ':true';     // Group 2, modifiy it
       });

console.log(newString);

产量

{Product{id{$lt:10,$gt:20},title:true,other:true,categories/{id:true,name:true}}}
© www.soinside.com 2019 - 2024. All rights reserved.