繁体   English   中英

正则表达式:Java中的负向后看+前瞻

[英]Regex: Negative Lookbehind + Lookahead in Javascript

我将尽力围绕可在服务器端使用的此正则表达式。

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
    }
}

}

我正在尝试使其成为客户端。

我认为这可以解决您的问题

 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) 

不确定您要获得的结果,但这是您的正则表达式
而不使用后向断言。
如果您有兴趣,整个想法是移动比赛位置
除了您不想匹配的东西。

做到这一点。

 (?:                           # -------------
      ( : \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}}}

暂无
暂无

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

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